in reply to grep usage confusion

grep returns a list. In scalar context (my $index = ... for example) a list returns the count of elements in the list. Writing my ($index) = ... makes $index the first member of a one element list and grep's return list is in list context so the first element of grep's list is assigned to the first element of the left hand side list - $index.

$_ is always an alias to each element in the list for grep, map and in a for loop (whatever you use as the loop variable is the alias in the case of a for loop). In the first case you provide a list of numbers: 0 .. $#coins (indexes into the array). In the second case you provide a list of elements - the elements of @coins.

grep's "second parameter" is always a list. You provided two different lists in your sample code. The range operator generates a list.

Note that most often grep expressions are written using a block: grep {$_ ne "fourthy"} @coins.


Perl reduces RSI - it saves typing

Replies are listed 'Best First'.
Re^2: grep usage confusion
by JavaFan (Canon) on Oct 14, 2008 at 06:57 UTC
    grep returns a list. In scalar context (my $index = ... for example) a list returns the count of elements in the list.
    No, it doesn' work that way. There is no list in scalar context - it is, afterall, scalar context. Lists only exist in list context. It is grep that returns the number of matches in scalar context.

    If it were true that functions returned lists, and lists in scalar context return the count of elements, then none of the following would work the way they do now:

    my $formatted_time = localtime; my $last_element = (10, 11, 12); my $package = caller; my $success = stat "/etc/passwd"; ...