http://qs1969.pair.com?node_id=690825


in reply to Re: Common hash keys
in thread Common hash keys

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

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

    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