Answers to Chapter 4 Exercises
Here’s one way to do it:
sub total { my $sum; # private variable foreach (@_) { $sum += $_; } $sum; }This subroutine uses
$sumto keep a running total. At the start of the subroutine,$sumisundefsince it’s a new variable. Then, theforeachloop steps through the parameter list (from@_) using$_as the control variable. (There’s no automatic connection among@_, the parameter array, and$_, the default variable for theforeachloop.)The first time through the
foreachloop, the first number (in$_) is added to$sum.$sumisundefsince nothing has been stored there. Since we’re using it as a number, which Perl sees because of the numeric operator+=, Perl acts as if it’s already initialized to0. Perl thus adds the first parameter to0, and puts the total back into$sum.Next time through the loop, the next parameter is added to
$sum, which is no longerundef. The sum is placed back into$sumand on through the rest of the parameters. Finally, the last line returns$sumto the caller.There’s a potential bug in this subroutine depending on how you think of things. Suppose this subroutine was called with an empty parameter list as we considered with the rewritten subroutine
&maxin the chapter text. In that case,$sumwould beundefwhich would be the return value. But in this subroutine, it would probably be more correct to return0as the sum of the empty list rather thanundef. (If you wished to distinguish the sum of an empty list from the sum of, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access