in reply to pass by reference
Perl subroutines are always call-by-reference.
produces 10 11.my $a = 10; print "$a "; change($a); print "$a"; sub change { $_[0]++; }
The standard practice of making copies of the subroutine parameters functionally turns this into call-by-value.
produces 10 10.my $a = 10; print "$a "; change($a); print "$a"; sub change { my $param = shift; $param++; }
But if you're passing an explicit reference, then a copy of the reference still refers to the original referent.
produces 10 11.# 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}++; }
...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.
produces 10 4.my $a = 10; my $b = \$a; my $c = 4; print "$$b "; change($b); print "$$b"; sub change { $_[0] = \$c; }
You usually won't write code like the first or last examples -- but it's good to understand all this.
|
|---|