Subroutines
Define and call
A subroutine is a named block of code introduced with the sub keyword. Call it by name with parentheses around the arguments; the ampersand form from very old code is optional and best forgotten.
sub greet {
my ($name) = @_;
return "hello, $name";
}
print greet("Ada"), "\n"; # hello, Ada
perl demo.pl
hello, Ada
Arguments arrive in the array @_, which the next lesson takes apart. Here the list assignment copies the first argument into $name and ignores the rest.
Return values
return leaves the subroutine immediately with the given value. Without a return, the value of the last expression is used, which is convenient for short functions and confusing for long ones.
sub max {
my ($a, $b) = @_;
return $a if $a >= $b;
$b;
}
print max(3, 9), "\n"; # 9
perl demo.pl
9
Calling return with no argument gives an empty list in list context and undef in scalar context. Say return; when the point is an early exit, and return undef; never, because it surprises list callers.
Where to put the sub
A call to a subroutine with parentheses works anywhere, because the parentheses tell the parser it is a call. A call without parentheses must come after the definition, or you need an empty prototype or a forward declaration.
sub double { return $_[0] * 2 }
print double(21), "\n"; # 42
print double 21, "\n"; # 42, no parentheses needed here
print "\n"; # the call above had no newline: "\n" is an argument
perl demo.pl
42
42
The safest habit is to put every sub at the bottom of the file and call with parentheses. The program then reads top to bottom as a story, with the details below.
Private subroutines
A leading underscore marks a helper that is not part of the public interface. Nothing enforces the rule, but every Perl programmer reads the underscore the same way.
sub _trim {
my ($s) = @_;
$s =~ s/^\s+|\s+$//g;
return $s;
}
In a later lesson the same idea becomes a real module, where the leading underscore combines with the export list so that other files cannot see the helper at all.
Next: Arguments in @_
Article author: Arthur Isaev