Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: A Simple hash question

by zigdon (Deacon)
on Oct 01, 2006 at 13:20 UTC ( #575775=note: print w/replies, xml ) Need Help??


in reply to A Simple hash question

The question doesn't have an answer, because your initial hash cannot exist. Hash keys have to be unique, otherwise they overwrite each other. So after your initial assignment, %pets looks like this:
%pets = ( 'pony' => 2, 'cat' => 2, 'dog' => 2 );
Now, if you had the original list assigned into an array, that would be a different story:
#!/usr/bin/perl -w use strict; my @pets = ("dog", 1, "cat", 2, "pony", 2, "dog", 2); my %pets; while (@pets) { my $key = shift @pets; my $val = shift @pets; $pets{$key} += $val; } foreach (sort keys %pets) { print "$_: $pets{$_}\n"; }
Hope that helps!

-- zigdon

Replies are listed 'Best First'.
Re^2: A Simple hash question
by chinamox (Scribe) on Oct 01, 2006 at 15:45 UTC
    Thank you! I will try it with the array and then pass it into a hash for a later opperation.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2019-06-25 17:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (107 votes). Check out past polls.

    Notices?