Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Common hash keys

by casiano (Pilgrim)
on Jun 07, 2008 at 10:01 UTC ( #690822=note: print w/ replies, xml ) Need Help??


in reply to Common hash keys

If you want to know which keys they have in common:

DB<1> %a = (a => 1, b =>2, c => 3); %b = (b =>2, c => 1, d => 4) DB<2> $seen{$_}++ for (keys(%a), keys(%b)) DB<3> x grep { $seen{$_} > 1 } keys(%seen) 0 'c' 1 'b'
If the only thing you want is to know if they have some key in common:
DB<1> use List::Util qw{first} DB<2> %a = (a => 1, b =>2, c => 3); %b = (b =>2, c => 1, d => 4) DB<3> x first { ++$seen{$_} > 1 } (keys(%a), keys(%b)) 0 'c'
Hope it helps


Comment on Re: Common hash keys
Select or Download Code
Re^2: Common hash keys
by FunkyMonk (Canon) on Jun 07, 2008 at 10:41 UTC
    DB<2> $seen{$_}++ for (keys(%a), keys(%b)) DB<3> x grep { $seen{$_} > 1 } keys(%seen)
    You can combine these two into a single statement:
    use Data::Dump; my %a = ( a => 1, b => 2, c => 3 ); my %b = ( b => 2, c => 1, d => 4 ); my %seen; pp grep { $seen{$_}++ } keys %a, keys %b;

    Update: Don't use state variables for this. See lodin's reply

    Or, with 5.10

    pp grep { state %seen; $seen{$_}++ } keys %a, keys %b;

    Unless I state otherwise, all my code runs with strict and warnings

      Be careful with that state. It won't do what (I think) you want.

      use 5.010; sub foo { my ($a, $b) = @_; sort grep { state %seen; $seen{$_}++ } keys %$a, keys %$b } my %a = ( a => 1, b => 2, c => 3 ); my %b = ( b => 2, c => 1, d => 4 ); say join ' ', foo(\%a, \%b); say join ' ', foo(\%a, \%b); __END__ b c a b b c c d
      Here you should just stick with my.

      lodin

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-08-01 23:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Who would be the most fun to work for?















    Results (51 votes), past polls