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 $_?

  • Comment on [Answered]: Grep: What is the reason following example code gives same result for both shift and $_?
  • Download Code

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

    See the documentation for @_ and shift. Those two in combination should explain it quite well, I think.

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

    Because the argument happened to be $_ (digit_sum_is_odd($_)).

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
    no, your idea is not right... $_ is not really how args get passed, $_ is global and so in this codd its the same $_ in the sub and in the grep. "shift" shifts @_, and @_ is the args of the sub, in your code @_ is always just ($_) so thats why its the same here
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
    Thank you Anonymous Monk and Hippo for your reply. I understand it better now.
    @_ is the way parameters are passed to subroutines, always! I was unable to figure out why $_ is also working but I know it now.