如何使用 EVAL 将参数传递给子例程?

Ste*_*ieD 12 raku

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

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

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

sub blah() { say 'running blah'; };
Run Code Online (Sandbox Code Playgroud)

我得到running blah输出。

但这是我所得到的。我尝试过各种方法,但没有看到明显的方法来传递@subscommands给该blah函数。

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

小智 11

我认为EVAL这里并不是绝对必要的。您可以进行间接查找,即

&::($cmd)(@sub-commands);
Run Code Online (Sandbox Code Playgroud)

此时&::($cmd),函数&blah已从字符串中查找出来$cmd并可供使用;然后我们用 来调用它@sub-commands

然后我们有

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

sub blah(*@args) {
    say "running `blah` with `{@args}`";
}
Run Code Online (Sandbox Code Playgroud)

并运行为

$ raku ./program blah this and that
Run Code Online (Sandbox Code Playgroud)

给出

running `blah` with `this and that`
Run Code Online (Sandbox Code Playgroud)


Eli*_*sen 6

制作MAIN多重也可能是一个解决方案:

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

  • 多么神奇的语言啊...您的意思是“@rest[]”或“{@rest}”,或者可能是其他方式,我不知道,因为Raku-is-amazing: ) (2认同)