Perl300 has asked for the wisdom of the Perl Monks concerning the following question:
While learning list operators (v5.26.1), I found this textbook example for grep:
#!/home/localperl/bin/perl use strict; use warnings; my @input_numbers = (1, 2, 4, 8, 16, 32, 64); my @odd_digit_sum = grep digit_sum_is_odd($_), @input_numbers; print "@odd_digit_sum\n"; sub digit_sum_is_odd { my $input = shift; # Can use $_ instead of shift print "\$input: $input\n"; my @digits = split //, $input; my $sum; $sum += $_ for @digits; return $sum % 2; }
I have tried using $_ instead of shift in the above example and it gives same result. So what I have guessed is:
When "sub digit_sum_is_odd" is called the parameter that is passed for each element of @input_numbers is interpreted as an array of single element, if shift is used.
When "sub digit_sum_is_odd" is called the parameter that is passed for each element of @input_numbers is interpreted as a scalar, if $_ is used.
Is this guess correct or am I mistaken? I would like to know what is the reason it gives same result for both shift and $_?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Grep: What is the reason following example code gives same result for both shift and $_?
by hippo (Archbishop) on Oct 09, 2017 at 21:31 UTC | |
|
Re: [Answered]: Grep: What is the reason following example code gives same result for both shift and $_?
by ikegami (Patriarch) on Oct 09, 2017 at 23:23 UTC | |
|
Re: Grep: What is the reason following example code gives same result for both shift and $_?
by Anonymous Monk on Oct 09, 2017 at 21:31 UTC | |
|
Re: Grep: What is the reason following example code gives same result for both shift and $_?
by Perl300 (Friar) on Oct 09, 2017 at 22:02 UTC |