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

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.