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

Maybe
my @keys_in_commmon = grep $hashref1->{$_}, keys %$hashref2;
would've sufficed?? If you just have to determine if they have keys in common,
if( grep $hashref1->{$_}, keys %$hashref2 ) { ... }
would do the trick...

Replies are listed 'Best First'.
Re^5: Common hash keys
by Anonymous Monk on Jun 08, 2008 at 06:56 UTC
    I would say  my @keys_in_commmon = grepexists($hashref1->{$_}), keys %$hashref2; to avoid autovivification.

      massa's code does not actually cause autovivification (perl 5.8.8) ...

      use warnings; use strict; use Data::Dumper; my %p; my %q = ( 1 => undef ); print Dumper( 'before', \%p ); my $r = grep $p{ $_ }, keys %q; print Dumper( 'after', \%p );

      ... I was also suspicious of autovivification but had to test that myself.

      The exists test is so that the case where a key has undef as a value, not to aviode auto vivification. Undef itself cannot be a key in a hash. But '0' and '' can.

        I've seen this "use exists() to avoid autovivification" misconception around a lot. I suspect it comes from this statement in exists:

        The element is not autovivified if it doesn’t exist.

        Other similar functions like defined don't have any such statement, leading people to believe that those somehow do autovivify elements, which in turn leads to unnecessarily complicated code like

          my $foo_in_hash = exists $hash{foo} && defined $hash{foo};

        I'm not sure why that disclaimer is there in the first place. Surely it's never meaningful to talk about autovivifying elements, since autovivification is about the silent creation of actual hashes and arrays, not their contents? And this also leads some people to think exists doesn't autovivify things at all, which it certainly does (as indeed the documentation goes on to explain... but some people never read past the first paragraph!)

        This is one of those little nitpicks I'm often tempted to submit a bug report about, but I'm never quite convinced it's really serious enough to warrant it. (And I'm not 100% confident it's wrong! I'm painfully conscious there's still a heck of a lot left for me to learn about Perl.)