简体   繁体   中英

Perl inserts unwanted keys in hashes

I keep having this problem with Perl and it's really getting annoying.

Platform: Mac OS X 10.7; Perl v5.12.3

Sample script

#!/usr/bin/perl

undef %hash;

@letters = qw / a b c /;
@numbers = qw / 1 2 3 /;

for($i=0;$i<=2;$i++){
    $hash{$letters[$i]}=$numbers[$i];
}

foreach $key (%hash) {
    print $key."\n";
}

For some scripts I get the first output (extra keys), sometimes I get the other (extra values)

Output:

a
a
b
b
c
c

or

1
2
3
a
b
c

Is this a 'feature' of Perl? How do I fix it?

Thanks!

You're missing the keys keyword to get the keys from the hash.

for my $key (keys %hash) {
    print $key."\n";
}

Otherwise, the hash gets flatted into a list, and returns all the keys and values.

The answer that suggests using 'keys' is correct, i just wanted to remind you to always put 'use strict;' and 'use warnings;' at the beginning of your scripts.

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