Prints: camelmy @test = qw(camel aplaca peguin aplaca monkey camel camel"); my @redundant; for (@test) { next if grep ("$_", @redundant); push (@redundant, $_); } print "@redundant\n";
Update: zdog asked about this in a private CB message so here goes. tomhukins is not quite correct in his description of the problem. What happens is this:
grep ("$_", @redundant) in a scalar context returns the number of times the expression $_ is true for all the elements of @redundant. But the first time through, there are no elements in @redundant so $_ is evaluated zero times.
So the first time through the loop, the "next if" fails and "camel" is pushed onto @redundant. Each time through the loop after than, @redundant does contain an element and the grep in a scalar context returns 1 meaning "for the one element in @redundant, $_ (the element 'camel') is true."
(Note: I am aware of the discussion about whether to say that grep always returns a list but that a list in scalar context evaluates to the number of elements or whether to say that grep in a scalar context returns a number. perlfunc says: "In scalar context, [grep] returns the number of times the expression was true.")
In reply to Re: (zdog) Re: Finding Redundant values in arrays
by dvergin
in thread Finding Redundant values in arrays
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |