I've read that perl uses call-by-reference when executing subrutines. I made a simple piece of code to check this property, but it behaves like if perl was call-by-value:
$x=50;
$y=70;
sub interchange {
($x1, $y1) = @_;
$z1 = $x1;
$x1 = $y1;
$y1 = $z1;
print "x1:$x1 y1:$y1\n";
}
&interchange ($x, $y);
print "x:$x y:$y\n";
This produces the following output:
$ perl example.pl
x1:70 y1:50
x:50 y:70
If arguments were treated in a call-by-reference way, shouldn't x be equal to x1 and y equal to y1?
I'm just starting with Perl as well, and I believe you're misunderstanding just what you're passing to the subroutine. When you pass $x and $y you are passing the scalars $x and $y are set to. You need to explicitly pass a reference, which also happens to be a scalar (being the only thing are ever allowed to pass to subroutines). I understand where you're coming from in thinking things are call-by-reference since for arrays and hashes, since you need to pass references to those.
This code should do what you're looking for:
I pass in references to $x and $y using \$x and \$y. Then, I use $$x and $$y to dereference them within the subroutine.
Perl is always definitely call by reference. You're statement
($x1, $y1) = @_
is copying the original argument values, since @_ holds aliases to the original parameters.From perlsub manpage:
To modify the values outside of the sub, you would have to modify the values of
@_
.The following
sub interchange
does modify the values:This gives the output:
More info here: http://www.cs.cf.ac.uk/Dave/PERL/node51.html
But, to quote the article: