PERL / CHAPTER 03
Iteration and function boundaries
IntermediateTrace loop aliases and pass explicit inputs into a subroutine.
By the end of this chapter
- Iterate over a list
- Extract subroutine arguments
- Recognize when a loop variable aliases an element
The idea
Enter with arrays and lexical variables understood. A for loop can iterate directly over list elements. When the list contains actual array elements, the loop variable aliases each element, so assigning through it can change the original array. This is useful when intentional and surprising when a programmer assumes the variable is always an independent copy. Read-only iteration should avoid assigning to the alias.
Subroutines receive arguments through @_. A common clear pattern copies needed arguments into lexical variables at the beginning, then returns a documented result explicitly. Copying scalar numeric arguments separates those local bindings from the caller’s scalar values. References require different reasoning because copying a reference still identifies the same underlying data. Keep the function’s mutation contract visible, especially when it accepts collection references.
use strict; use warnings;
sub total {
my @numbers=@_;
my $sum=0;
for my $n (@numbers) { $sum += $n; }
return $sum;
}
print total(2,5,4), "\n";11
The subroutine copies its scalar arguments into a local array and accumulates them without assigning to the loop alias.
Try it yourself
Write a subroutine that counts values strictly greater than a supplied limit.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING