如果perl是按引用调用,为什么会发生这种情况? [英] If perl is call-by-reference why does this happen?

查看:98
本文介绍了如果perl是按引用调用,为什么会发生这种情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆