【问题标题】:How can I use EVAL to pass arguments to subroutines?如何使用 EVAL 将参数传递给子例程?
【发布时间】:2022-01-16 03:07:11
【问题描述】:

我正在尝试使用 Raku,并试图弄清楚如何使用子命令编写程序。当我跑步时,./this_program blah

#! /usr/bin/env raku
use v6;

sub MAIN($cmd, *@subcommands) {
    $cmd.EVAL;
}

sub blah() { say 'running blah'; };

我得到running blah 输出。

但这是我所得到的。我尝试了各种方法,但我看不到将@subscommands 传递给blah 函数的明显方法。

我什至不确定EVAL 是否也是可行的方法,但我找不到任何其他解决方案。

【问题讨论】:

标签: raku


【解决方案1】:

我认为EVAL 在这里并不是绝对必要的。你可以去indirect lookup,即,

&::($cmd)(@sub-commands);

&::($cmd)点,从字符串$cmd中查找函数&blah,即可使用;然后我们用@sub-commands 调用它。

那么我们有

sub MAIN($cmd, *@sub-commands) {
    &::($cmd)(@sub-commands);
}

sub blah(*@args) {
    say "running `blah` with `{@args}`";
}

运行方式

$ raku ./program blah this and that

给予

running `blah` with `this and that`

【讨论】:

    【解决方案2】:

    MAIN 设为 multi 也可能是一种解决方案:

    multi sub MAIN('blah', *@rest) {
        say "running blah with: @rest[]";
    }
    multi sub MAIN('frobnicate', $this) {
        say "frobnicating $this";
    }
    

    【讨论】:

    • 多么神奇的语言...你的意思是@rest[]{@rest} 还是可能-some-other-way-that-I-don't-know-because-Raku-is-太棒了:)
    • @我的意思不是@rest[] :-) 已修复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 2016-11-22
    • 2021-03-09
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多