arg 1的类型必须是block或sub {}(不是子例程条目)

时间:2019-02-20 11:39:03

标签: perl functional-programming

以下Python代码演示了我要在Perl中执行的操作:

work True
runner: hello
work False

输出:

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);

我认为将其移植到Perl很简单。因此,我从以下代码开始:

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函数传递给private static final String SELECT_QUERY = "SELECT" + " new MyObjectDto(object.id, object.time)" + " FROM ObjectEntity object" + " WHERE object.msgDateTime < :startDateTime "; @Override public ScrollableCursor getScrollableCursor(LocalDateTime startDateTime) { TypedQuery<ScrollableCursor> query = createQuery(SELECT_QUERY, ScrollableCursor.class) .setParameter("startDateTime", startDateTime) .setHint(QueryHints.SCROLLABLE_CURSOR, HintValues.TRUE); return query.getSingleResult(); } ,但无济于事。

我想念什么?

1 个答案:

答案 0 :(得分:5)

您尝试过吗:

runner \&$work, "hello";

或者只是停止使用原型并这样做:

runner $work, "hello";

Perl中的原型适用于您希望对子程序进行某种神奇的调用解析的过程,例如一些内置的get。它们不适合像其他语言一样仅用于参数检查。