Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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

In reply to Re^5: Array to hash converstion by dsheroh
in thread Array to hash converstion by gem555

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-28 23:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found