The issue you've run into here is that each hash key can only be associated with a single value, so the second assignment to
$hash{one} overwrites its previous value. Or, as spazm put it in the comment you were replying to,
My solutions below assume that you have unique key values, or are un-interested in collisions. In the case of a collision, the last reference to the key wins.
However, the single value held by the hash doesn't have to be a simple scalar. If you use an array reference there (giving you a "hash of arrays" or "HoA"), then the code will be a little more complex, but you'll be able to store as many values as you like with each key:
#!/usr/bin/perl
use strict;
use warnings;
my @value_pairs = qw( one abc two xyz one def );
my %hash;
while (@value_pairs) {
my $key = shift @value_pairs;
my $value = shift @value_pairs;
push @{$hash{$key}}, $value;
}
for my $key (keys %hash) {
print "key $key has values: ", join(', ', @{$hash{$key}}), "\n";
}
__END__
key one has values: abc, def
key two has values: xyz
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.