Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Hello, I have started to work through the Intermediate Perl book after the Learning Perl book. I really enjoyed the Learning Perl book, it was pretty clear and readable. The Intermediate seems less clear and I am already stuck in the second chapter on a grep example:

my @odd_digit_sum = grep digit_sum_is_odd($_), @input numbers; sub digit_sum_is_odd { my $input = shift; my @digits = split //, $input; my $sum; $sum += $_ for @digits; return $sum % 2; }

The book gives @input_numbers = (1, 2, 4, 8, 16, 32, 64), and says that the @odd_digit_sum resulting from the grep code will give 1, 16, and 32. I must be an idiot, because I do not understand this example( and the book really does not explain it). If grep places each value of @input_numbers into $_ one at a time, how does it ever sum anything??

I thought maybe it calls the subroutine with the entire list (even though this is not how grep is supposed to work), but even then, the answer of 1, 16 and 32 does not make sense to me. I know grep will give the answers when sum % 2 is not zero, but if you start with 1, then add 2, you get 3 which gives non-zero result, so grep should give 2 also. Still do not understand how it sums anything, given that $_ gets a single value one at a time?! Really confused, any help would be appreciated!! Thanks!

In reply to do not understand grep example by live4tech

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?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2023-04-01 05:19 GMT
Find Nodes?
    Voting Booth?

    No recent polls found