gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:25:00 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com