如果你喜欢更多的风格,那就试试吧Tie::Cfg
.样品:
tie my %conf, 'Tie::Cfg', READ => "/etc/connect.cfg";
$conf{test}="this is a test";
Run Code Online (Sandbox Code Playgroud)
最好的方法是使用CPAN中的可用模块,就像其他人建议的那样.以下只是为了您自己的理解,假设您有这样的ini文件:
$ more test.ini
[Section1]
s1tag1=s1value1 # some comments
[Section2]
s2tag1=s2value1 # some comments
s2tag2=s2value2
[Section3]
s3tag1=s3value1
Run Code Online (Sandbox Code Playgroud)
您可以使用Perl的正则表达式(或字符串方法)+哈希等数据结构来自行解析w/o模块.
示例代码:
$ini="test.ini";
open (INI, "$ini") || die "Can't open $ini: $!\n";
while (<INI>) {
chomp;
if (/^\s*\[(\w+)\].*/) {
$section = $1;
}
if (/^\W*(\w+)=?(\w+)\W*(#.*)?$/) {
$keyword = $1;
$value = $2 ;
# put them into hash
$hash{$section} = [ $keyword, $value];
}
}
close (INI);
while( my( $k, $v ) = each( %hash ) ) {
print "$k => " . $hash{$k}->[0]."\n";
print "$k => " . $hash{$k}->[1]."\n";
}
Run Code Online (Sandbox Code Playgroud)
产量
$ perl perl.pl
Section1 => s1tag1
Section1 => s1value1
Section3 => s3tag1
Section3 => s3value1
Section2 => s2tag2
Section2 => s2value2
Run Code Online (Sandbox Code Playgroud)
Config :: Tiny非常简单易用.
$Config = Config::Tiny->read( 'file.conf' );
my $one = $Config->{section}->{one};
my $Foo = $Config->{section}->{Foo};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25634 次 |
最近记录: |