我有这个配置文件
dbUser=customer
dbPass=passwrd
dbSid=customer.shadow
passwdFile=/production/etc-user
tmpUsers=tmpuser
htpasswd=/usr/local/apache2/bin/htpasswd
Run Code Online (Sandbox Code Playgroud)
然后是一个读取配置文件的脚本:
#!/usr/local/bin/perl
use warnings;
use strict;
readConfig();
# reads in a config file
sub readConfig {
my $configFile = $ARGV[0];
my %prefs ="" ;
open (CONFIG, "< $configFile") or die "Cannot open $configFile for reading: $!\n";
while (<CONFIG>) {
chomp; # kill newlines
s/#.*//; # ignore comments
s/^\s+//; # ignore leading whitespace
s/\s+$//; # ignore trailing whitespace
next unless length;
my($var,$value) = split(/\s*=\s*/, $_, 2);
$prefs{$var} = $value;
print "$var : $prefs{$var}\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我得到一个奇怪的错误 - 哈希assignemnt中奇数个元素:
bash-3.00$ /tmp/config_foo /production/cfg/users.cfg
Odd number of elements in hash assignment at /tmp/config_foo line 10.
dbUser : customer
dbPass : passwd
dbSid : customer.shadow
passwdFile : /production/etc-users1
tmpUsers : tmpuser
htpasswd : /usr/local/apache2/bin/htpasswd
bash-3.00$
bash-3.00$
Run Code Online (Sandbox Code Playgroud)
my %prefs = "";
Run Code Online (Sandbox Code Playgroud)
是导致错误的行.应使用具有偶数个元素的列表初始化哈希.你可以写
my %prefs = ();
Run Code Online (Sandbox Code Playgroud)
但是没有理由,因为
my %prefs;
Run Code Online (Sandbox Code Playgroud)
做同样的事情.
只是用 my %prefs;
当你说:
my %prefs ="" ;
Run Code Online (Sandbox Code Playgroud)
您正在使用此结构创建哈希.
$VAR1 = {
'' => undef
};
Run Code Online (Sandbox Code Playgroud)
这是一个使用子程序代码的小演示:
use warnings;
use strict;
my %prefs;
while (<DATA>) {
chomp; # kill newlines
s/#.*//; # ignore comments
s/^\s+//; # ignore leading whitespace
s/\s+$//; # ignore trailing whitespace
next unless length;
my($var,$value) = split(/\s*=\s*/, $_, 2);
$prefs{$var} = $value;
print "$var : $prefs{$var}\n";
}
__DATA__
dbUser=customer
dbPass=passwrd
dbSid=customer.shadow
passwdFile=/production/etc-user
tmpUsers=tmpuser
htpasswd=/usr/local/apache2/bin/htpasswd
Run Code Online (Sandbox Code Playgroud)
它输出
dbUser : customer
dbPass : passwrd
dbSid : customer.shadow
passwdFile : /production/etc-user
tmpUsers : tmpuser
htpasswd : /usr/local/apache2/bin/htpasswd
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2219 次 |
| 最近记录: |