Subroutines and Arguments
Default Arguments
A subroutine can fill in a missing argument with a default value.
default argument
A default argument supplies a fallback when the caller omits a value.
Default Arguments
default_arguments.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;
sub count_label {
my ($count, $noun) = @_;
$noun //= "item";
my $label = $count == 1 ? $noun : $noun . "s";
return "$count $label";
}
my $count = 1;
my $text = count_label($count);
print "count=$count\n";
print "text=$text\n";
use strict;
use warnings;
sub count_label {
my ($count, $noun) = @_;
$noun //= "item";
my $label = $count == 1 ? $noun : $noun . "s";
return "$count $label";
}
my $count = 0;
my $text = count_label($count);
print "count=$count\n";
print "text=$text\n";
use strict;
use warnings;
sub count_label {
my ($count, $noun) = @_;
$noun //= "item";
my $label = $count == 1 ? $noun : $noun . "s";
return "$count $label";
}
my $count = 3;
my $text = count_label($count);
print "count=$count\n";
print "text=$text\n";
$count ← 1
11my $count→ 1 = 1; #@count=0, 312my $text = count_label($count1);$count ← 1, $noun ← (empty), $label ← item
4sub count_label {5 my ($count→ 1, $noun→ (empty)) = @_;6 $noun→ item //= "item";7 my $label→ item = $count1 == 1 ? $noun→ item : $noun . "s";8 return "$count1 $labelitem";9}$text ← 1 item
11my $count = 1; #@count=0, 312my $text→ 1 item = count_label($count1);1314print "count=$count1\n";15print "text=$text1 item\n";outputcount=1 text=1 item
$count ← 0
11my $count→ 0 = 0;12my $text = count_label($count0);$count ← 0, $noun ← (empty), $label ← items
4sub count_label {5 my ($count→ 0, $noun→ (empty)) = @_;6 $noun→ item //= "item";7 my $label→ items = $count0 == 1 ? $noun→ item : $noun . "s";8 return "$count0 $labelitems";9}$text ← 0 items
11my $count = 0;12my $text→ 0 items = count_label($count0);1314print "count=$count0\n";15print "text=$text0 items\n";outputcount=0 text=0 items
$count ← 3
11my $count→ 3 = 3;12my $text = count_label($count3);$count ← 3, $noun ← (empty), $label ← items
4sub count_label {5 my ($count→ 3, $noun→ (empty)) = @_;6 $noun→ item //= "item";7 my $label→ items = $count3 == 1 ? $noun→ item : $noun . "s";8 return "$count3 $labelitems";9}$text ← 3 items
11my $count = 3;12my $text→ 3 items = count_label($count3);1314print "count=$count3\n";15print "text=$text3 items\n";outputcount=3 text=3 items