http://qs1969.pair.com?node_id=1214240

yueli711 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, Below is the program to calculate average value. I really do not understand why the value of "count" will change. Thanks in advance!

use strict; use warnings; sub total { my $sum; foreach (@_){ $sum += $_; } $sum; } sub average { if (@_==0){return} my $count=@_; my $sum =total(@_); $sum/$count; }

Replies are listed 'Best First'.
Re: why the value of count will be change?
by toolic (Bishop) on May 09, 2018 at 00:25 UTC
    My question is why the value of count is just the number of the data in @?
    The reason is found in List value constructors:
    Note that the value of an actual array in scalar context is the length of the array; the following assigns the value 3 to $foo:
    @foo = ('cc', '-E', $bar);
    $foo = @foo; # $foo gets 3

      Thank you so much!

Re: why the value of count will be change?
by LanX (Saint) on May 08, 2018 at 23:51 UTC
    Because Perl does call by reference

    The elements in @_ are aliases, you should copy them first.

    From perlglossary

    • alias
    A nickname for something, which behaves in all ways as though you’d used the original name instead of the nickname. Temporary aliases are implicitly created in the loop variable for foreach loops, in the $_ variable for map or grep operators, in $a and $b during sort’s comparison function, and in each element of @_ for the actual arguments of a subroutine call. Permanent aliases are explicitly created in packages by importingsymbols or by assignment to typeglobs. Lexically scoped aliases for package variables are explicitly created by the our declaration.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Wikisyntax for the Monastery

    PS: And for god's sake, please use indentation!

      Thank you so much! My question is why the value of count is just the number of the data in @? Thank you in advance!

Re: why the value of count will be change?
by Marshall (Canon) on May 09, 2018 at 01:39 UTC
    I do not see any calling program for subs: total() and average().

    Can you show a calling program and also the data?