Beefy Boxes and Bandwidth Generously Provided by pair Networks
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
in thread do not understand grep example by live4tech

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2023-03-23 02:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (60 votes). Check out past polls.

    Notices?