Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: A Simple hash question

by zigdon (Deacon)
on Oct 01, 2006 at 13:20 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://575775]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (2)
As of 2024-04-24 15:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found