convenientstore has asked for the wisdom of the Perl Monks concerning the following question:

Hi, can someone please explain the $_ in the bottom?
I am trying to get a better understanding of grep and
below $_ seems to be bit hard to understand
Does $_ iterate over and over for @skipper so that it will evauluate like below

preserver eq blue_shirt
preserver eq hat
preserver eq jacket
preserver eq perserver ==> returns 1

I was thinking since it was iterating over @required , I thought $_ would be from @required.
but I am guessing since grep does expression, $_ becomes from @skipper?
my @required = qw(preserver sunscreen water_bottle jacket); my @skipper = qw(blue_shirt hat jacket preserver sunscreen); for my $item (@required) { unless (grep $item eq $_, @skipper) { # not found in list? print "skipper is missing $item.\n"; } }

Replies are listed 'Best First'.
Re: grep and $_
by grep (Monsignor) on Aug 11, 2007 at 23:26 UTC
    In your case, $_ is an alias (think pronoun) for the current list value being iterated in the closest loop.

    I think the main problem you are having is the implicit loop that grep creates. grep actually creates another loop which sets $_.

    Also your outside loop over @required never sets $_ since you explicitly create a variable.

    ex.

    my @required = qw(preserver sunscreen water_bottle jacket); foreach my $item (@required) { print "$_\n"; ## You just get a warning }
      no wonder I coudn't print $_
      thanks guys
        you can if you use the BLOCK form of grep..
        unless ( grep { print "$item eq $_? ", $item eq $_, "\n"; $item eq $_; } @skipper ) { # not found in list? print "skipper is missing $item.\n"; }
Re: grep and $_
by bruceb3 (Pilgrim) on Aug 11, 2007 at 23:24 UTC
    Basically you are right. $_ iterates over @skipper, which happens for each element of the @required list. Adding some print statements help show what is happening.
    my @required = qw(preserver sunscreen water_bottle jacket); my @skipper = qw(blue_shirt hat jacket preserver sunscreen); for my $item (@required) { print "$item\n"; unless (grep $item eq $_, @skipper) { # not found in list? print "skipper is missing $item.\n"; } }
    The variable $item has each value from the @required list. In scalar context grep will return the number of times that the expression was true. $_ is an aliases to the element in the @skipper list.