![]() |
|
go ahead... be a heretic | |
PerlMonks |
comment on |
( #3333=superdoc: print w/replies, xml ) | Need Help?? |
Grep is not something I understand perfectly, so this answer may be corrected by the more knowledgeable, but I'll try anyway. Grep takes two arguments, the condition and the list. The list is the array. The condition is the subroutine that you provide. So each element in turn becomes $_ (the default variable), but before being passed to grep, the sub is evaluated using $_. Sequentially, 1 becomes $_. This is passed through the sub which returns 1 (true) without changing $_. Grep therefore includes 1 (the value of $_, not true) in its output. Then it passes 2. The sub returns 0 (false) and 2 is ignored by grep. Ditto 4 and 8. When $_ becomes 16, the sub will return 1 (true) again without changing $_ and 16 will be pushed into the output array. The important thing to understand is the working of $_. It is the value that grep is currently considering and it is also the value passed to the sub as the test parameter that grep will use to decide if $_ should be in the output. Note the line in the sub my $input = shift;. This makes a copy of the value of $_ for internal use in the sub, thus ensuring that $_ does not get changed. Regards, John Davies In reply to Re: do not understand grep example
by davies
|
|