Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re^4: Array to hash converstion

by gem555 (Acolyte)
on Jul 15, 2009 at 07:03 UTC ( #780180=note: print w/replies, xml ) Need Help??

in reply to Re^3: Array to hash converstion
in thread Array to hash converstion

#!/usr/bin/perl -w use strict; my @value_pairs = qw (one abc two xyz); my %hash = @value_pairs; foreach my $key (keys %hash) { print "key $key is $hash{$key}\n"; } __END__ prints: key one is abc key two is xyz key one is def
If two keys are same then, output is
key one is abc key two is xyz
so for the key one value is def is not printed here. The expected output is
key one is abc key two is xyz key one is def
Please tell me how can I get the output like this

Replies are listed 'Best First'.
Re^5: Array to hash converstion
by dsheroh (Prior) on Jul 15, 2009 at 09:41 UTC
    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
      $correction = $data_pair->{value} if($data_pair->{key} eq 'correct');
      how to store the value in $correction only if the $data_pair->{value} is not empty.
        check to see if it is empty (whatever that means :D)
        $correction = $data_pair->{value} if exists $data_pair->{value} and # could be undef defined $data_pair->{value} and # at least "" length $data_pair->{value} and # has length $data_pair->{value} and # has true value $data_pair->{key} eq 'correct';

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://780180]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2020-07-06 03:49 GMT
Find Nodes?
    Voting Booth?

    No recent polls found