Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: do not understand grep example

by BrowserUk (Patriarch)
on Jun 15, 2012 at 17:38 UTC ( #976469=note: print w/replies, xml ) Need Help??


in reply to do not understand grep example

The grep line my @odd_digit_sum = grep digit_sum_is_odd($_), @input numbers;

passes each number into the subroutine using $_. Within the subroutine that value is assigned to $input:

my $input = shift;

The digits of each number are then split into the array @digits

my @digits = split //, $input;

At this point, if $input is 32; then @digits contains: ( '3', '2' ).

Those digits are then summed

$sum += $_ for @digits;

giving 5, and then tested to see if the result is odd:

return $sum % 2;

Which in the case of 32 is true, so true is returned to grep and grep allows that input (32) through to the results array.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Replies are listed 'Best First'.
Re^2: do not understand grep example
by live4tech (Sexton) on Jun 16, 2012 at 06:28 UTC

    Thank you all for your responses, the Monastery has not failed me yet!

    BrowserUk, your response provided me with the answer. I realized that my issue was not with grep, but rather with split. I did not realize that split using null (split //) would split by character (e.g. "32" would become 3, 2).

    Now I see when the summing takes place. The book glossed over this, but it would have been nice if it had just noted that to jog my memory, which is not so great anymore.

    Thank you!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2023-01-28 14:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?