Hi tom2112,

Here's another way you could do it, which yields 4 arrays at the end, the union of the hash keys, the keys found only in hash1, those found only in hash2, and the intersection (found in both hashes).

I commented it fairly thoroughly in the hopes that it would help you during the initial stages of the Perl-learning process.

use strict; use warnings; # Create two test hashes, with some matching keys, and some keys only +in # the first or second hash. # my %hash1 = ( 'a' => 1, 'b' => 2, 'd' => 3, 'f' => 4, 'h' => 5 ); my %hash2 = ( 'a' => 1, 'c' => 2, 'd' => 3, 'e' => 5, 'g' => 6 ); # Get the union of the two hashes, and save it in an array (@union) my %union = map { $_ => 1 } (keys %hash1, keys %hash2); my @union = keys %union; # Declare arrays for values only in %hash1, values only in %hash2, and # values found in both (the intesection). ## my (@hash1, @hash2, @inter); # For each item in the intersection, construct a flag which identifies # which array to save it in. # foreach (@union) { my $flag = (exists $hash1{$_}? 1: 0) + (exists $hash2{$_}? 2: 0); (1 == $flag) and push @hash1, $_; (2 == $flag) and push @hash2, $_; (3 == $flag) and push @inter, $_; } # Display the results print "[Results]\n"; printf "Union ........... %s\n", join(',', sort @union); printf "Intersection .... %s\n", join(',', sort @inter); printf "Only in hash1 ... %s\n", join(',', sort @hash1); printf "Only in hash2 ... %s\n", join(',', sort @hash2); __DATA__ [Results] Union ........... a,b,c,d,e,f,g,h Intersection .... a,d Only in hash1 ... b,f,h Only in hash2 ... c,e,g

s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

In reply to Re: Need advice on hashes and methods by liverpole
in thread Need advice on hashes and methods by tom2112

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.