Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Common hash keys

by throop (Chaplain)
on Jun 07, 2008 at 13:23 UTC ( [id://690834]=note: print w/replies, xml ) Need Help??


in reply to Common hash keys

use strict; use vars qw($hashRef1 $hashRef2); #code that puts values into the hashes my @keyIntersection = grep exists($hashRef2->{$_}), keys %$hashRef1; # Or if you just want to know if there are any use List::Util; my $hasInt = first {exists $hashRef2->{$_}} keys %$hashRef1;
$hasInt will be undef unless there's an intersection.
But be careful, it will be 0 if the first interecting key is '0'

throop

Replies are listed 'Best First'.
Re^2: Common hash keys
by lodin (Hermit) on Jun 08, 2008 at 06:37 UTC

    There's no need to be careful if you handle the 0 case directly:

    use List::Util; my $hasInt = defined first { exists $hashRef2->{$_} } keys %$hashRef1 ;

    lodin

      Actually, there's no need to be careful or test for definedness.

      List::Util::first() returns the result of the code block, in this case the boolean return of the exists function. The values associated with the keys never come into it.

      use List::Util qw[ first ];; my $a = { a=>0, b=>0, c=>0 }; my $b = { c=>0, d=>0, e=>0 }; if( first{ exists $b->{ $_ } } keys %$a ) { print "Common keys!"; } Common keys!

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        List::Util::first() returns the result of the code block, in this case the boolean return of the exists function.
        i think it returns the key it's iterating over, just like grep works. from the docs: "first returns the first element where the result from BLOCK is a true value."
        use List::Util qw[ first ]; my $a = { 0 => 0 }; my $b = { 0 => 0 }; if( first{ exists $b->{ $_ } } keys %$a ) { print "Common keys!"; }
        prints nothing.
Re^2: Common hash keys
by Anonymous Monk on Jun 07, 2008 at 18:55 UTC

    *That's the one*. Thank you.

    use List::Util 'first'; if(first{exists $hashRef2->{$_}} keys %$hashRef1 ) # }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-26 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found