Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: do not understand grep example

by davies (Vicar)
on Jun 15, 2012 at 17:41 UTC ( #976470=note: print w/ replies, xml ) Need Help??


in reply to do not understand grep example

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


Comment on Re: do not understand grep example
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://976470]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (17)
As of 2014-12-18 13:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (52 votes), past polls