my $a = 10;
print "$a ";
change($a);
print "$a";
sub change {
$_[0]++;
}
produces 10 11.
The standard practice of making copies of the subroutine parameters functionally turns this into call-by-value.
my $a = 10;
print "$a ";
change($a);
print "$a";
sub change {
my $param = shift;
$param++;
}
produces 10 10.
But if you're passing an explicit reference, then a copy of the reference still refers to the original referent.
# contrived example: there usually isn't a good reason
# to have references to scalars.
my $a = 10;
my $b = \$a;
print "$$b ";
change($b);
print "$$b";
sub change {
my $param = shift;
${$param}++;
}
produces
10 11.
...but the subroutine parameter was still an alias of the original reference, and so its value (not just the referent's value) can be changed, just as in the first example.
my $a = 10;
my $b = \$a;
my $c = 4;
print "$$b ";
change($b);
print "$$b";
sub change {
$_[0] = \$c;
}
produces 10 4.
You usually won't write code like the first or last examples -- but it's good to understand all this.
|