September 2017
Beginner
402 pages
9h 52m
English
A sub taking arguments uses them in its body. By default, the sub's arguments are read-only values; it is not possible to modify the values inside the sub, as shown in the following code:
sub f($a) { $a = 0; } my $x = 10; f($x);
This leads to the following error:
Cannot assign to a readonly variable ($a) or a value
There are a couple of ways of overcoming that, depending on how you intend to use the modified value. If the modified argument is only needed inside the sub, then create a copy of it, as shown here:
sub f($a) {
my $b = $a;
$b = 0;
say "b = $b";
}
my $x = 10;
f($x); # b = 0
To avoid creating temporary variables, it is better to mark the sub's argument by appending the is copy trait as follows:
sub f($a is copy) ...
Read now
Unlock full access