The perlfaq describes intersection of two arrays. I feel this is a better solution for intersecting arrays than what is mentioned in the faq.

The faq is constantly updated to provide good answers but it is not perfect. More importantly, it gives example code for certain situations, that can be easily adapted to others.

BTW: the link you inserted brought me to another incarnation of PM: this is annoying. To put it in a way that will be agnostic, just use [id://2461] or [id://2461|this], which will render respectively like How can I find the union/difference/intersection of two arrays? and this respectively.

However, I am looking to intersect hashes.

Hashes are functions: their keys can be regarded as sets. Sets have intersections, functions generally not. (But possibly in some particular branch of Mathematics.) Judging from your code and using intechangeably the word "hash" and the word "function", you want the restriction of the first hash to the intersection of its domain with that of the second one. The idiom in Perl for such a restriction is a slice which will work like thus: @hash1{LIST}. (A slice will also do more, but let's set that aside for the moment.) The given LIST can be simply built with grep. Thus:

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

In reply to Re^3: Intersect two hashes by blazar
in thread Intersect two hashes by HarshaHegde

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.