Why is the array shifted at the beginning of the subroutine?
sub max {
my($max_so_far) = shift @_;
foreach (@_) {
if ($_ > $max_so_far) {
$max_so_far = $_;
}
}
$max_so_far;
}
Is it just to give $max_so_far an initial value? The program runs exactly the same with
my($max_so_far) = undef;
Is there a particular reason to shift the array to start with? (I ask because I spent about 10 min trying to figure out why that shift was essential to the subroutine.)
It’s to initialise the return value for the function and something the rest of the function can compare against.
Consider some scenarios and trace through the code. For example, say it is invoked like this:
Inside max, the first line sets $max_so_far to 1 and @_ becomes (2,3). Now when we run through the foreach loop we have an initial value and avoid undef errors. It first compares $max_so_far to 2, updates it to 2, and so on.
Another example is if max is invoked like this:
Inside max, the first line sets $max_so_far to 1 and @_ becomes (). When we hit the foreach loop, it has nothing to iterate through and just returns the initial value $max_so_far.
Another example is if max is invoked like this:
Inside max, the first line sets $max_so_far to undef because @_ is empty. There’s nothing to iterate through in the foreach loop, so the function just returns undef.