我是 perl 的新手,并且有一些范围或语法问题。
我正在尝试编写一段代码,从文件中读取行,将它们在某个定界符处分成两部分,然后将每一半存储为哈希中的键值对。这是我的代码:
#!/usr/bin/perl
use strict;
use warnings;
my $filename = $ARGV[0];
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
my @config_pairs;
while (my $row = <$fh>) {
chomp ($row);
push (@config_pairs, $row);
}
my %config_data;
for my $pair (@config_pairs) {
my ($key, $value) = split(/\s*=\s*/, $pair);
%config_data{$key} = $value;
}
for my $k (%config_data) {
print "$k is %config_data{$k}";
}
当我尝试运行它时,我得到:
$ perl test_config_reader.pl --config.txt
"my" variable %config_data masks earlier declaration in same scope at test_email_reader.pl line 22.
syntax error at test_config_reader.pl line 19, near "%config_data{"
Global symbol "$value" requires explicit package name at test_email_reader.pl line 19.
Execution of test_config_reader.pl aborted due to compilation errors.
我不确定我做错了什么。显然我还不明白 perl 是如何工作的。
最佳答案
运行脚本时,我收到不同的消息:
Can't modify key/value hash slice in list assignment at ./1.pl line 19, near "$value;"
Global symbol "$key" requires explicit package name (did you forget to declare "my $key"?) at ./1.pl line 23.
Execution of ./1.pl aborted due to compilation errors.
要引用单个哈希值,请将符号从
%
更改为至 $
(想想“复数”与“单数”):$config_data{$key} = $value;
# ...
print "$k is $config_data{$k}";
另外,
$k
和 $key
是不同的变量(您似乎同时解决了这个问题)。要迭代散列,请使用 keys :
for my $k (keys %config_data) {
否则,您也会遍历这些值。
关于perl - for 循环的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32744979/