in reply to Comparing two arrays (was: any smart ideas??:)

If you just want the intersection of the two arrays and all values are unique within each array, something like this should work:
#!/usr/bin/perl -w use strict; my @array1 = qw[a b c d e]; my @array2 = qw[a n o t h e r]; my %count; foreach my $element (@array1, @array2) { $count{$element} += 1; } foreach my $key (keys %count) { print "$key appears in both arrays\n" if $count{$key} == 2; }
Output:
$ ./foo.pl a appears in both arrays e appears in both arrays
For something a little more complex (but also more robust, more flexible, and probably faster) you could do this:
#!/usr/bin/perl -w use strict; my @array1 = qw[a b c d e]; my @array2 = qw[t e s t d a t a]; my @sort1 = sort @array1; my @sort2 = sort @array2; while (@sort1 && @sort2) { if ($sort1[0] eq $sort2[0]) { my $match = $sort1[0]; while (@sort1 && $sort1[0] eq $match) { shift @sort1; } while (@sort2 && $sort2[0] eq $match) { shift @sort2; } print "$match is in both arrays\n"; } elsif ($sort1[0] lt $sort2[0]) { shift @sort1; } else { shift @sort2; } }
which produces
$ ./bar.pl a is in both arrays d is in both arrays e is in both arrays
without getting a false positive on 't' like the first version would.