如果perl是按引用调用,为什么会发生这种情况? [英] If perl is call-by-reference why does this happen?
问题描述
我读到perl在执行子例程时使用按引用调用.我编写了一段简单的代码来检查此属性,但是它的行为就像perl是按值调用一样:
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";
这将产生以下输出:
$ perl example.pl
x1:70 y1:50
x:50 y:70
如果通过按引用调用方式处理参数,则x不应等于x1且y等于y1吗?
If arguments were treated in a call-by-reference way, shouldn't x be equal to x1 and y equal to y1?
推荐答案
要修改子项之外的值,您必须修改@_
的值.
To modify the values outside of the sub, you would have to modify the values of @_
.
以下sub interchange
做修改值:
sub interchange {
($x1, $y1) = @_; # this line copies the values to 2 new variables
$z1 = $x1;
$x1 = $y1;
$y1 = $z1;
$_[0] = $x1; # this line added to change value outside sub
$_[1] = $y1; # this line added to change value outside sub
print "x1:$x1 y1:$y1\n";
}
这给出了输出:
x1:70 y1:50
x:70 y:50
此处的更多信息: http://www.cs.cf. ac.uk/Dave/PERL/node51.html
但是,引用这篇文章:
您可以看到该函数能够影响主程序中的@array变量.通常,这被认为是不好的编程习惯,因为它没有将函数的功能与程序的其余部分隔离开来.
You can see that the function was able to affect the @array variable in the main program. Generally, this is considered bad programming practice because it does not isolate what the function does from the rest of the program.
这篇关于如果perl是按引用调用,为什么会发生这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!