我读到 perl 在执行子程序时使用引用调用。我写了一段简单的代码来检查这个属性,但它的行为就像 perl 是按值调用:
$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";
这会产生以下输出:
$ perl example.pl
x1:70 y1:50
x:50 y:70
如果以引用调用的方式处理参数,x 不应该等于 x1 而 y 不应该等于 y1 吗?
最佳答案
Perl 总是明确地通过引用调用。您声明 ($x1, $y1) = @_
是复制原始参数值,因为@_ 持有原始参数的别名。
来自 perlsub 手册页:
Any arguments passed in show up in the array @_ . Therefore, if you called a function with two arguments, those would be stored in $[0] and $[1] . The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).
关于perl - 如果 perl 是按引用调用,为什么会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063638/