Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope issue with for loops

I am new to perl, and am having some scope or syntax issues.

I am trying to write a piece of code that reads lines from a file, splits them up at a certain delimiter into two pieces, and then stores each half as a key value pair 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 and 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 am not sure what I am doing wrong. Clearly I don't understand how perl works yet.

like image 747
Max G. Avatar asked Jan 07 '23 12:01

Max G.


1 Answers

I'm getting 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.

To refer to a single hash value, change the sigil from % to $ (think "plural" versus "singular"):

$config_data{$key} = $value;
# ...
print "$k is $config_data{$k}";

Also, $k and $key are different variables (you seem to have fixed this in the meantime).

To iterate over a hash, use keys:

for my $k (keys %config_data) {

Otherwise, you'll loop over the values, too.

like image 100
choroba Avatar answered Jan 18 '23 17:01

choroba