Another simple way, without deleting all those keys, is simply to check for existence as in the code snippet, below. It's mostly comments. The code is small.

#!/bin/perl use strict; use warnings; # We create two lists my @list1 = ( 1, 2, 3, 4, 5, 6, 7, 8, 9 ); my @list2 = ( 1, 3, 5, 7, 9, 11, 13, 15 ); # Let's convert them into hashes so # we can check for existence. We # set the value equal to 1, since # we don't need to count them. my %hash1 = map { $_ => 1 } @list1; my %hash2 = map { $_ => 1 } @list2; # Here's the fun part. Let's create an array/list # of all the keys in hash1 that aren't in hash2. # This is the same as items in list 1 that aren't # in list 2. my @list1_minus_list2 = grep { !exists $hash2{$_} } sort keys %hash1; # Let's do it again. Let's create an array/list # of all the keys in hash1 that aren't in hash1. # This is the same as items in list 2 that aren't # in list 1. my @list2_minus_list1 = grep { !exists $hash1{$_} } sort keys %hash2; # Let's print them out nicely. print join( ',', @list1_minus_list2 ), "\n"; print join( ',', @list2_minus_list1 ), "\n"; __END__ # Results 2,4,6,8 11,13,15

Update:To find the intersection, change the !exists to exists. To create a union, simply create one hash from both lists with my %union_hash = map { $_ => 1 } (@list1,@list2);. Then just extract the keys with something like my @union_list = sort keys %union_hash;

Hope this helped,
-v.

"Perl. There is no substitute."

In reply to Re: Need advice on hashes and methods by Velaki
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.