perl - 有没有更好的方法在 Perl 中通过引用传递?

标签 perl parameters pass-by-reference parameter-passing perl-module

我正在做这样的传递引用:

use strict;
use warnings;

sub repl {
    local *line = \$_[0]; our $line;
    $line = "new value";
}

sub doRepl {
    my ($replFunc) = @_;
    my $foo = "old value";
    $replFunc->($foo);
    print $foo; # prints "new value";
}

doRepl(\&repl);

有更清洁的方法吗?

原型(prototype)不起作用,因为我使用的是函数引用(相信我,使用函数引用是有充分理由的)。

我也不想用$_[0]无处不在repl因为它很丑。

最佳答案

你看过Data::Alias ?它允许您使用干净的语法创建词法范围的别名。

您可以使用它来创建传递引用语义,如下所示:

use strict;
use warnings;

use Data::Alias;

sub foo {
    alias my ($arg) = @_;
    $arg++;
}

my $count = 0;

foo($count);

print "$count\n";

输出为 1 ,表示调用foo修改了它的论点。

关于perl - 有没有更好的方法在 Perl 中通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464692/

相关文章:

perl - POSIX 模块的问题

c++ - 从参数和范围返回

c - 警告 : ‘struct tag’ declared inside parameter list will not be visible outside of this definition or declaration void func(struct tag v);

c++ - 如何在方法中获取 int 数组(方法参数)的长度?

perl - 使用 curl 发布 Gzip 压缩数据

perl - 如何在Perl中伪造STDIN?

python - 当变量引用同一个对象时,它是如何调用的,为什么python有这个特性?

c - 我很难使用引用传递

regex - 如何在perl中提取一部分行

c++ - 如果我用一个struct来携带argc和argv,我该如何将地址argv赋值给结构体内部的一个变量呢?