Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: how can i return the common keys from a hash

by perladdict (Chaplain)
on Aug 04, 2006 at 22:02 UTC ( #565758=note: print w/ replies, xml ) Need Help??


in reply to how can i return the common keys from a hash

If u want to return the common keys from hashes,use the fallowing sub to pass hash ref as arguments to sub.

@repeat=common(\%a,\%b,\%c); sub common { my %d; for my $href(@_) { while(my $m=each %$href) $d{$m}++; } } return grep {$d{$_} ==@_} keys %d }


Comment on Re: how can i return the common keys from a hash
Download Code
Re^2: how can i return the common keys from a hash
by ivancho (Hermit) on Aug 05, 2006 at 01:19 UTC
    I am somewhat puzzled by the following DWIM:

    in scalar context, each returns the next key of the hash. Why doesn't, then, the assignment "my $m = each %$href" return false if the key is "0"? ie

    > perl -wle 'my %a = ( 0 => 1, y => 2, z => 4); while (my $m = each %a +) { print $m }' y 0 z > perl -wle 'my @a = ( 0 => 1, y => 2, z => 4); while (my $m = pop @a) + { print $m }' 4 z 2 y 1 > perl -wle 'my @a = ( 0 => 1, y => 2, z => 4); while (my $m = shift @ +a) { print $m }' >
      perl -MO=Deparse -wle 'my %a = ( 0 => 1, y => 2, z => 4); while (my $m + = each %a) { print $m }' BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } my(%a) = (0, 1, 'y', 2, 'z', 4); while (defined(my $m = each %a)) { print $m; }
      It checks for defined as the loop condition, not a true value.
        indeed, as that's what you want in 99% of the cases..
        I was mostly pointing out that it's neither logical, nor obvious from docs

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2015-07-06 05:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (70 votes), past polls