[plug] Perl: Intersection of two arrays?

Derek Fountain derekfountain at yahoo.co.uk
Tue Jun 24 21:36:41 WST 2003


On Tuesday 24 June 2003 20:35, Arie Hol wrote:
> At 05:23 PM 24-06-2003 +0800, you wrote:
> >Given two arrays (in Perl) with string values, I need to derive an array
> > of the elements in both. I'd like to do this quickly, too. ^_^
>
> Have you tried :
>
> @new_array = @array1 . @array2;

That creates an array with one element, that element being a string containing 
digits. The digits represent the lengths of the two arrays.

> OR maybe :
>
> foreach $string (@array2)
>         {
>         push(@array1, $string);
>         }

That's a slow way of appending the values of @array2 to the end of @array1. 
Like 'push @array1, @array2', only with a (seemingly pointless) loop.

> Or maybe :
>
> @array1 .= @array2;

I can't figure that one out. Is it legal?

You appear to be confused by the OP's badly worded question. To get "an array 
of the elements in both", the simplest way is simply to flatten:

@result = (@array1, @array2);

To get the intersection of two arrays, as per the subject, using an 
intermediate hash as a lookup table is the easiest way.

-- 
"...our desktop is falling behind stability-wise and feature wise to KDE 
...when I went to Mexico in December to the facility where we launched gnome, 
they had all switched to KDE3." - Miguel de Icaza, March 2003



More information about the plug mailing list