我有一个类似以下内容的文件
[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的初学者请在这里帮助我。
答案 0 :(得分:1)
使用AppConfig
:
#!/usr/bin/perl
use strict;
use warnings;
use AppConfig qw/:argcount/;
use Data::Dumper;
my $config = AppConfig->new( { CREATE => 1, GLOBAL => { ARGCOUNT => ARGCOUNT_ONE } } );
$config->file( \*DATA );
my %amrit = $config->varlist( '^amrit_' );
print Dumper \%amrit;
print $config->get( 'amrit_type' ), "\n";
$config->set( 'amrit_type', 'enemy' );
print $config->get( 'amrit_type' ), "\n";
__DATA__
[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
答案 1 :(得分:1)
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