是否有更优雅的方式来处理来自命令行参数的输入,或者STDIN如果命令行上没有给出任何文件?我目前正在这样做:
sub MAIN(*@opt-files, Bool :$debug, ... other named options ...) {
# note that parentheses are mandatory here for some reason
my $input = @opt-files ?? ([~] .IO.slurp for @opt-files) !! $*IN.slurp;
... process $input ...
}
Run Code Online (Sandbox Code Playgroud)
而且还不错,但我想知道我是否缺少一些更简单的方法?
msc*_*cha 11
我可能会选择一个multi sub MAIN,比如:
multi sub MAIN(Bool :$debug)
{
process-input($*IN.slurp);
}
multi sub MAIN(*@opt-files, Bool :$debug)
{
process-input($_.IO.slurp) for @opt-files;
}
Run Code Online (Sandbox Code Playgroud)
我可能会做两件事来改变这一点。我会分手??!! 到不同的行,我会去一个完整的方法链:
sub MAIN(*@opt-files, Bool :$debug, ... other named options ...) {
my $input = @opt-files
?? @opt-files».IO».slurp.join
!! $*IN.slurp;
... process $input ...
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用 @opt-files.map(*.IO.slurp).join
编辑:以ugexe 的答案为基础,你可以做
sub MAIN(*@opt-files, Bool :$debug, ... other named options ...) {
# Default to $*IN if not files
@opt-files ||= '-';
my $input = @opt-files».IO».slurp.join
... process $input ...
}
Run Code Online (Sandbox Code Playgroud)