Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: do not understand grep example

by davies (Prior)
on Jun 15, 2012 at 17:41 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found