perl - 如果 perl 是按引用调用,为什么会发生这种情况?

标签 perl pass-by-reference call-by-value evaluation-strategy

我读到 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/

相关文章:

perl - 如何将 Atom 转换为 RSS?

perl - 安装 perl 模块时如何运行配置脚本?

c++ - 通过构造函数传递的引用定义类成员

C# 核心 3.1 ByRef 和 ByVal

c - 这个调用在 C 中是通过引用调用还是通过值调用?

perl - Perl 中的嵌套函数调用

sql - Perl、DBI 和 SQL : Why NOT does not work in some SQL queries?

arrays - 函数是否可以更改在其他地方声明的字符串数组 slice 的大小?戈兰

c - 按值调用和按引用调用都有效吗?

java - 重新排列 ArrayList 的顺序