live4tech has asked for the wisdom of the Perl Monks concerning the following question:
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 nonzero 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!


Replies are listed 'Best First'.  

Re: do not understand grep example
by BrowserUk (Patriarch) on Jun 15, 2012 at 17:38 UTC  
by live4tech (Sexton) on Jun 16, 2012 at 06:28 UTC  
Re: do not understand grep example
by moritz (Cardinal) on Jun 15, 2012 at 17:29 UTC  
Re: do not understand grep example
by tobyink (Canon) on Jun 15, 2012 at 18:45 UTC  
Re: do not understand grep example
by davies (Prior) on Jun 15, 2012 at 17:41 UTC 