for循环的范围问题

Max*_* G. 4 perl hash scope split for-loop

我是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}";
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行时,我得到:

$ 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.
Run Code Online (Sandbox Code Playgroud)

我不确定我做错了什么.很明显我不明白perl是如何工作的.

cho*_*oba 9

我在运行脚本时收到不同的消息:

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.
Run Code Online (Sandbox Code Playgroud)

要引用单个哈希值,请将sigil更改%$(认为​​"复数"与"单数"):

$config_data{$key} = $value;
# ...
print "$k is $config_data{$k}";
Run Code Online (Sandbox Code Playgroud)

此外,$k并且$key是不同的变量(你似乎在此期间修复了这个).

要迭代哈希,请使用:

for my $k (keys %config_data) {
Run Code Online (Sandbox Code Playgroud)

否则,你也会循环遍历这些值.

  • @Sobrique:不用急着:) (2认同)