in reply to Need advice on hashes and methods

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."