http://www.perlmonks.org?node_id=86716


in reply to (zdog) Re: Finding Redundant values in arrays
in thread Finding Redundant values in arrays

Oops! You are mistaken...
my @test = qw(camel aplaca peguin aplaca monkey camel camel"); my @redundant; for (@test) { next if grep ("$_", @redundant); push (@redundant, $_); } print "@redundant\n";
Prints: camel

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

Replies are listed 'Best First'.
Re: Re: (zdog) Re: Finding Redundant values in arrays
by IraTarball (Monk) on Jun 08, 2001 at 00:36 UTC
    This is broken, notice that it just prints the first element of the @test array? So aplaca doesn't print. In fact if you put peguin as the first element of test it prints peguin. The problem is that you're trying to be to terse. The $_ that you're using in the grep is not the $_ that aliases an element of @test, it's the $_ that aliases an element of @redundant (grep uses $_ too). So you're saying next if there's an element of redundant that matches an element of redundant. Probably not really what your were thinking of.

    Update: Well, it was broken. I started getting down votes for this node, I guess 'cause it's no longer applicable.

    :) Ira

    "So... What do all these little arrows mean?"
    ~unknown