chinamox has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I just started tinkering with Perl a few days ago and I have a basic question about manipulating a hash.

if if generate the hash from the os...

%pets = ("dog", 1, "cat", 2, "pony", 2, "dog", 2,)

now I want it to be transformed into

%pets = ("dog", 3, "cat", 2, "pony", 2,)

Is there a simple way to do this? Thank you for any help.

Replies are listed 'Best First'.
Re: A Simple hash question
by zigdon (Deacon) on Oct 01, 2006 at 13:20 UTC
    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

      Thank you! I will try it with the array and then pass it into a hash for a later opperation.
Re: A Simple hash question
by marto (Cardinal) on Oct 01, 2006 at 13:04 UTC
Re: A Simple hash question
by CountZero (Bishop) on Oct 01, 2006 at 14:40 UTC
    use Data::Dumper; %pets = ("dog", 1, "cat", 2, "pony", 2, "dog", 2,); print Dumper(\%pets); $pets{dog}=3; print Dumper(\%pets);
    gives you:
    $VAR1 = { 'pony' => 2, 'cat' => 2, 'dog' => 2 }; $VAR1 = { 'pony' => 2, 'cat' => 2, 'dog' => 3 };
    Data::Dumper is your friend!

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

      Thank you, I will read up on Data::Dumper and buy you a drink the next time I run into you in the Gentalman Looser!
        You will easily recognize me as I will be wearing my mirrorshades.

        CountZero

        "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law