Cornelis Swanepoel wrote: >> > Are you trying to find the intersection of two arrays? I believe this >> > is covered in the FAQ, > > > For simply finding the intersection of two arrays, is there something > wrong > with using nested greps? > > I'm a Perl beginner and after reading the first post I wrote this: > > my @arrA = qw( 1 3 5 6); > my @arrB = qw( 2 3 6 4); > my $tmp; > > my @matches = grep { $tmp = $_; > grep $tmp == $_, @arrB; > } @arrA; > > print join " ", @matches, "\n"; > > It prints out > 3 6 > for the above arrays. > > I've read the perlfaq snippet and it seems to be more elegant and flexible. > I'd just like to know if there are any reasons, ie efficiency,
Yes, the FAQ answer is more efficient. Using Big O notation[1], the FAQ's solution is O(n) and your's is O(n**2) > I shouldn't > use nested greps on simple lists like the above. On simple lists it shouldn't make much of a difference. > As I said, I am a Perl beginner and only want to deepen my understanding > here so any comments would be greatly appreciated. Limit the scope of the $tmp variable to the code block: my @matches = grep { my $tmp = $_; grep $tmp == $_, @arrB; } @arrA; [1] http://en.wikipedia.org/wiki/Big_O_notation John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>