Scope for cycles

I am new to perl and I have problems with scope or syntax.

I am trying to write a piece of code that reads lines from a file, splits them into a specific separator into two parts, and then saves each half as a pair of key values ​​in a hash. This is my code:

#!/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}";
}

When I try to run this, I get:

$ 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.

I'm not sure what I'm doing wrong. Clearly, I do not understand how perl works.

+4
source share
1 answer

I get different messages when running the script:

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) {

.

+9

Source: https://habr.com/ru/post/1608706/


All Articles