简体   繁体   中英

Why does my first hash value disappear in Perl?

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

Perl hash can only have unique keys, so

$wordcount{2} = "apple";

is later overwritten by

$wordcount{2} = "cake";

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM