我有一个如下内容的文件
[amrit]
type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=22
[windwos]
type=friend
host=111.118.253.145
port=2775
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=50
[windwos121254]
type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=ulaw
allow=alaw
context=sip-calling
qualify=yes
call-limit=99
现在我想在 perl 中创建一个脚本。这将找到 [amrit] 这个标签下的所有行
type=friend
host=111.118.253.145
port=2776
username=amrit
secret=password
disallow=all
allow=gsm
context=sip-calling
qualify=yes
call-limit=22
现在我想更新每个字段的值,但值应该是这个标签的更改,只有我使用 perl 脚本找到这些行,但我无法更改这些字段的值。脚本如下
#!/usr/bin/perl
$count = 0;
open (IN, "file.txt");
while (<IN>) {
if (/\[amrit\]/) {
$count = 1;
}
elsif (/\[*\]/) {
$count = 0;
}
elsif ($count) {
print;
}
}
close IN;
现在我想更新 [amrit] 标签中每一行的值。我是 perl 的初学者,请在这里帮助我。
最佳答案
Config::Tiny在这里满足您的需求。
#! /usr/bin/perl -w
use strict;
use Config::Tiny;
my $config = Config::Tiny->read('test.ini');
my $section ="amrit";
print "[$section]\n";
foreach my $parameter (keys %{$config->{$section}})
{
print "\t$parameter = $config->{$section}->{$parameter}\n";
}
这里是读取特定标签数据的脚本。
你可以通过这个设置值
$Config->{section}->{username} = 'No user'; # Change a value
还有如下更有用的api
# Changing data
$Config->{newsection} = { this => 'that' }; # Add a section
$Config->{section}->{Foo} = 'Not Bar!'; # Change a value
delete $Config->{_}; # Delete a value or section
关于regex - 查找特定标签并在 perl 中替换其下的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21747000/