Consider this simple program. Can you explain why the output is different after uncommenting the first two lines? What is happening with my hash with use strict? How to fix the program to work with use strict?
echo -e "key1\nkey2\nkey3" | perl -lne '
#use strict; use warnings;
#my %hash;
BEGIN {
$hash{'key3'} = "value";
}
chomp;
if ($hash{$_}) {
print "$_ matched";
} else {
print "$_ unmatched ";
}
'
Output:
key1 unmatched
key2 unmatched
key3 matched
Using the
-nswitch implictly puts your entire program inside awhile (defined($_=<ARGV>)) { ...block, including yourmy %hashstatement:That is,
my %hashis redeclared in each iteration of the loop. To keep this as a one-liner and without making it too cumbersome, consider declaringour %hashto make%hasha package variable.