Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

why the value of count will be change?

by yueli711 (Sexton)
on May 08, 2018 at 23:42 UTC ( #1214240=perlquestion: print w/replies, xml ) Need Help??

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 (Sage) 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?

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2021-11-27 15:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?