in reply to Re^2: Intersect two hashes
in thread Intersect two hashes

I mentioned the FAQ because the only meaningful interpretation of "intersection" of two hashes is the intersection of their keys, which leads back to determining the intersection of two lists. I would code the loop a bit differently:

my @intersection = grep { exists $hash2{$_} } keys %hash1; my %intersection; @intersection{ @intersection } = @hash1{ @intersection };

Update: I made an error and had my %intersection where I should have assigned a hash slice instead. Fixed, thanks to ysth!

Update 2: Fixed a syntax error - you can't declare a hash slice via my. Spotted again by ysth!

Replies are listed 'Best First'.
Re^4: Intersect two hashes (initialize hash slice)
by ysth (Canon) on Jun 11, 2007 at 07:00 UTC
    you can't declare a hash slice via my
    You could have done
    @$_{ @intersection } = @hash1{ @intersection } for \my %intersection;
    but I don't know of any other one-statement way. Does Perl 6 provide a convenient syntax to declare a hash and initialize a slice of it in one swell foop?
Re^4: Intersect two hashes
by GrandFather (Saint) on Jun 10, 2007 at 21:19 UTC

    The task is slightly more interesting if you want to construct an intersection hash of the values that match. That may of course result in two keys for the same value in some cases. Maybe you'd want to key the intersection hash by the values from the original hash?

    I don't think OP tells us enough of the story really. A little XYish maybe?


    DWIM is Perl's answer to Gödel