Why does the first hash value disappear in Perl?
Why apple:2
does the hash remove the first value when printing the output?
use warnings;
use strict;
use Data::Dumper;
my @array = ("apple:2", "pie:4", "cake:2");
my %wordcount;
our $curword;
our $curnum;
foreach (@array) {
($curword, $curnum) = split(":",$_);
$wordcount{$curnum}=$curword;
}
print Dumper (\%wordcount);
+3
source to share
2 answers
What you probably wanted to do is:
use warnings;
use strict;
use Data::Dumper;
my @array = ("apple:2", "pie:4", "cake:2");
my %wordcount;
for my $entry (@array) {
my ($word, $num) = split /:/, $entry;
push @{$wordcount{$num}}, $word;
}
print Dumper (\%wordcount);
Thus, each entry in the %wordcount
bindings a number of words to an array of words that appear many times (assuming the symbol :n
in the notation indicates the number).
It's okay to be a beginner, but it's not okay to assume that other people can read your mind.
Also, don't use globals ( our
) with lexical scope ( my
).
+5
source to share