现在正好需要使用perl读写一些配置信息,就将读写config文件的方法汇总一下。
这个是最简单的方法 详细说明可以参照“<perl安装路径>/html/lib/Config/Tiny.html” 然后就可以通过下面的代码读写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 use Config:: Tiny ; my $Config = Config:: Tiny-> new ; $Config = Config:: Tiny-> read ( 'file.conf' ) ; my $rootproperty = $Config -> { _ } -> { rootproperty } ; my $one = $Config -> { section } -> { one } ; my $Foo = $Config -> { section } -> { Foo } ; $Config -> { newsection } = { this = > 'that' } ; $Config -> { section } -> { Foo } = 'Not Bar!' ; delete $Config -> { _ } ; $Config -> write ( 'file.conf' ) ;file.conf文件如下:
1 2 3 4 5 6 rootproperty = blah [section] one = twp three = four Foo = Bar empty =
示例如下:
1 2 3 4 5 6 7 8 use Configfile:: Ini ; my $settingsfile = 'test.ini' ; my $settings = new Configfile:: Ini ( $Settingsfile ) ; my %allsettings = $settings -> get_all_settings ; my %entry = $settings -> get_entry ( 'myentry' ) ; my $value = $settings -> get_entry_setting ( 'myentry' , 'thissetting' ) ;详细说明可以参考http://opensource.avajadi.org/configfile-ini/Ini.html
示例如下:
1 2 3 4 5 6 use strict ; use warnings ; use Config:: IniFiles ; my $cfg = new Config:: IniFiles ( - file = > "./config.ini" ) ; print "The value is " . $cfg -> val ( 'Section' , 'Parameter' ) . "." if $cfg -> val ( 'Section' , 'Parameter' ) ;详细说明可以参考http://bbs.chinaunix.net/thread-1071426-1-1.html中的4楼回复。
示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 use strict ; use Win32:: AdminMisc ; use Cwd ; my $dir = getcwd ; my $file = $dir . $ARGV [0 ] ; foreach my $section ( Win32:: AdminMisc:: ReadINI ( $file , "" , "" ) ) { foreach my $key ( Win32:: AdminMisc:: ReadINI ( $file , $section , "" ) ) { my $value = Win32:: AdminMisc:: ReadINI ( $file , $section , $key ) ; print "($key, $value)" , "n" ; } }详细说明可以参考http://blogold.chinaunix.net/u/29291/showart_344126.html中的第三种方法。
示例如下:
1 2 3 use IniParser ; my $ini = IniParser-> new ( "test.ini" ) ; my $inputdir = $ini -> expectEntry ( "Directories" , "Input" ) ;详细说明可以参考http://www.lwolf.cn/BLOG/article/program/perl-ini.html。
示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #!/usr/bin/perl -w open CONFIG , "config.ini" || die "open config $!n" ; $session = $ARGV [0 ] ; $key = $ARGV [1 ] ; $flag =0 ; while ( $string = ) { chomp $string ; if ( $flag == 0 && $string ! ~ / ^ [ $session ] / ) { next ; } $flag = 1 ; if ( ( $string ! ~ / ^ #/)&&(($k,$v) = $string =~ m/(w+)=(.*)/) ){ if ( $k eq $key ) { print "I find $k ............... value $vn" ; last ; } } else { next ; } if ( $string = ~ / ^ [ / ) { last ; } }config.ini文件如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 [perl1] # one = 1 two = 2 three = 3 # four = four = 4 five = asd ad 5 asdasdasd [per2] # one = 1 two = 2 three = 3 # four = four = 4 five = I am lipeng asdasdasd带参数执行:
1 2 C : UsersleniyDesktop1 > perl . pl perl1 two I find two . . . . . . . . . . . . . . . value 2详细说明可以参考http://hi.baidu.com/litaosmile/blog/item/72938859764aaf2d2934f04d.html。