Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comparing keys and values in different hashes

by Anonymous Monk
on Mar 03, 2003 at 13:59 UTC ( #240025=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, I basically want to compare the keys between two hashes to see which they have in common. If they have one in common I want to multiply the values of both keys together. I have managed to do the comparing part, but not sure how to multiply the values. Please can anyone help?? e.g. Ideal output;
dog = 55 cat = 12
The code;
my %hash = ( 'dog' => '5', 'sheep' => '10', 'cat' => '3', ); my %hash2 = ( 'dog' => '11', 'budgie' => '1', 'cat' => '4', ); foreach (keys %hash2) { if (exists $hash{$_}) { print "$_ exists"; } }

Comment on comparing keys and values in different hashes
Select or Download Code
Re: comparing keys and values in different hashes
by robartes (Priest) on Mar 03, 2003 at 14:04 UTC
    Have a look at perldata for the syntax to access hash values.

    CU
    Robartes-

Re: comparing keys and values in different hashes
by fruiture (Curate) on Mar 03, 2003 at 14:04 UTC

    You're very close:

    foreach( keys %hash2 ){ if( exists $hash1{$_} ){ print "$_ = ",$hash2{$_}*$hash1{$_},"\n"; } }

    btw.: please don't quote numbers (like '5') if you want them to be numbers and not strings: It's both confusing and (although only in microseconds) slows perl down.

    my %hash = ( dog => 11, budgie => 1, #... )
    --
    http://fruiture.de
Re: comparing keys and values in different hashes
by broquaint (Abbot) on Mar 03, 2003 at 14:06 UTC
    my %hash = ( dog => 5, sheep => 10, cat => 3, ); my %hash2 = ( dog => 11, budgie => 1, cat => 4, ); print "$_: ", $hash{$_} * $hash2{$_}, "\n" for grep exists $hash2{$_}, keys %hash; __output__ cat = 12 dog = 55
    Be careful not to stringify your numeric values or you could get unexpected results.
    HTH

    _________
    broquaint

Re: comparing keys and values in different hashes
by Russ (Deacon) on Mar 03, 2003 at 18:46 UTC
    This post may be interesting to you, in comparing two hashes.

    Synopsis:

    my %Diffs = ((map(($_ => [$R{$_}, undef]), grep {not exists $S{$_}} k +eys %R)), (map(($_ => [undef, $S{$_}]), grep {not exists $R{$_}} k +eys %S)), (map(($_ => [$R{$_}, $S{$_}]), grep {exists $S{$_} and $R +{$_} ne $S{$_}} keys %R)));

    Russ

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2014-11-26 11:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (168 votes), past polls