perl hash hash 中奇数个元素

标签 perl hash

我有这个配置文件

dbUser=customer
dbPass=passwrd
dbSid=customer.shadow
passwdFile=/production/etc-user
tmpUsers=tmpuser
htpasswd=/usr/local/apache2/bin/htpasswd

然后是一个读取配置文件的脚本:
#!/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";
        }
   }

我得到一个奇怪的错误 - 散列赋值中的元素数是奇数:
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$

最佳答案

my %prefs = "";

是导致错误的行。散列应该使用具有偶数个元素的列表进行初始化。你可以写
my %prefs = ();

但没有理由,因为
my %prefs;

做同样的事情。

关于perl hash hash 中奇数个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012900/

相关文章:

Perl LWP::UserAgent 在特定服务器上使 SSL 失败

r - 在 Perl 中更有效地处理 AoA 的笛卡尔积

string - 人类可读的短单向哈希用于模糊日志文件中的字符串?

arrays - Perl-将排序的数组元素读取到带有排序键的散列中

string - 是否可以将短子字符串与散列长字符串进行比较

perl - 为什么只有其中一个告诉我 "Modification of a read-only value attempted"?

perl - 如何使用 Test::WWW::Mechanize 进行授权

Perl Open 和 Flock 超时

MySQL更新另一列的md5

ruby-on-rails - 如何检查哈希中是否存在特定值?