Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Hash issues

by Nicpetbio23! (Acolyte)
on Jul 26, 2017 at 21:39 UTC ( [id://1196119]=perlquestion: print w/replies, xml ) Need Help??

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

I have two hashes.
%out : $key, $value %ret : $key1, $value1
If $value1 is equal to $key I want to print "$key1:$value1:$value\n" Why doesn't this work?
if ( $ret{$value1} eq $out{$key} ){ print "$ret{$key1}:$ret{$value1}:$out{$value}\n"; }

Replies are listed 'Best First'.
Re: Hash issues
by choroba (Cardinal) on Jul 26, 2017 at 21:56 UTC
    Make Perl tell you why it doesn't work:
    if ($ret{$value1} eq $out{$key}) { print "$ret{$key1}:$ret{$value1}:$out{$value}\n"; } else { print "'$ret{$value1}' and '$out{$key}' are different.\n"; }

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Hash issues
by huck (Prior) on Jul 26, 2017 at 21:51 UTC

    If $value1 is equal to $key I want to print "$key1:$value1:$value\n" Why doesn't this work?

    if you want to test what you said above you would say

    if ( $value1 eq $key ){ ...; }

Re: Hash issues
by roboticus (Chancellor) on Jul 26, 2017 at 22:06 UTC

    Nicpetbio23!:

    You don't reference a hash from the values, but from the keys. So $ret{$value1} isn't going to give you what you want. You really need something like $ret{$key1} to get value 1. So you probably want to create a reversed hash:

    my %reversed_ret = (reverse %ret);

    Then you can check for $reversed_ret{$value1}. Note: there's a problem with reversing a hash like this: If you have the same value1 for multiple keys, then that value will return only the last key you added to the reversed hash.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-24 02:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found