gpt4 book ai didi

perl - arg 1 的类型必须是 block 或 sub {}(不是子程序入口)

转载 作者:行者123 更新时间:2023-12-02 09:09:05 25 4
gpt4 key购买 nike

下面的 Python 代码演示了我想在 Perl 中做什么:

def runner(cmd, arg):
print("runner:", arg)
cmd()

def run_hooks1(arg):
def work():
print("work", arg)

if (arg):
work()
else:
runner(work, "hello")

run_hooks1(True)
run_hooks1(False)

输出:

work True
runner: hello
work False

我认为将它移植到 Perl 会很简单。所以我从这段代码开始:

sub runner(&$) {
my $cmd = shift;
my $arg = shift;
print STDOUT "runner: $arg\n";
&{$cmd}();
}

sub run_hooks1($) {
my $arg = shift;

sub work() {
print STDOUT "work: $arg\n";
}

if ($arg) {
work();
} else {
runner \&work, "hello";
}
}

run_hooks1(0);
run_hooks1(1);

不幸的是,这会导致:

Variable "$arg" will not stay shared at test.pl line 17.
runner: hello
work: 0
work: 0

由于这个警告,我重写了 run_hooks 如下:

sub run_hooks1($) {
my $arg = shift;

my $work = sub {
print STDOUT "work: $arg\n";
};

if ($arg) {
&{$work}();
} else {
runner &work, "hello";
}
}

但现在我得到:

Type of arg 1 to main::runner must be block or sub {} (not subroutine entry) at test.pl line 23, near ""hello";"
Execution of test.pl aborted due to compilation errors.

我尝试了多种其他方法将 work 函数传递给 runner 但无济于事。

我错过了什么?

最佳答案

你试过吗:

runner \&$work, "hello";

或者只是停止使用原型(prototype)并做:

runner $work, "hello";

Perl 中的原型(prototype)适用于当你想要对你的子程序调用进行某种神奇的解析时,就像一些内置的 get 一样。它们不适合像其他语言那样仅用于参数检查。

关于perl - arg 1 的类型必须是 block 或 sub {}(不是子程序入口),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785472/

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