Reputation: 41
Why does the hash remove the first value apple:2
when I print 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);
Upvotes: 3
Views: 162
Reputation: 118166
What you probably wanted to do was:
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);
This way, each entry in %wordcount
relates a word count to an array of the words which appear that many times (assuming the :n
in the notation indicates the count).
It is OK to be a beginner, but it is not OK to assume other people can read your mind.
Also, don't use global variables (our
) when lexically scoped (my
) will do.
Upvotes: 5
Reputation: 50677
Perl hash can only have unique keys, so
$wordcount{2} = "apple";
is later overwritten by
$wordcount{2} = "cake";
Upvotes: 8