在Perl 5中,我可以使用Getopt::Long
通过一些验证来解析命令行参数(请参见http://perldoc.perl.org/Getopt/Long.html中的以下内容。
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
GetOptions ("length=i" => \$length, # numeric
"file=s" => \$data, # string
"verbose" => \$verbose) # flag
or die("Error in command line arguments\n");
say $length;
say $data;
say $verbose;
=i
中的"length=i"
在与--length
相关联的值上创建数字类型约束,=s
中的"file=s"
创建类似的字符串类型约束。
我如何在Raku(néePerl 6)中做类似的事情?
该功能内置于Raku(以前称为Perl 6)中。这相当于您在Raku中的Getopt::Long
代码:
sub MAIN ( Str :$file = "file.dat"
, Num :$length = Num(24)
, Bool :$verbose = False
)
{
$file.say;
$length.say;
$verbose.say;
}
MAIN
是一个特殊的子例程,它根据其签名自动分析命令行参数。
Str
和Num
提供字符串和数字类型约束。
Bool
使$verbose
成为二进制标志,如果不存在或称为False
,则为--/verbose
。 (/
中的--/foo
为a common Unix command line syntax for setting an argument to False
。)>
False
放在子例程签名中的变量之前,使它们成为命名的参数(而不是位置的参数)。
使用:
后接默认值来提供默认值。
如果需要单个字符或其他别名,则可以使用$variable =
语法。
:f(:$foo)
sub MAIN ( Str :f(:$file) = "file.dat" , Num :l(:$length) = Num(24) , Bool :v(:$verbose) = False ) { $file.say; $length.say; $verbose.say; }
为:x(:$smth)
附加别名,例如本例中的短别名--smth
。也可以使用多个别名和全名,例如:-x
将使您获得:foo(:x(:bar(:y(:$baz))))
,--foo
,-x
,--bar
和-y
,并且如果有任何别名将传递给--baz
]。
$baz
也可以与位置参数一起使用。例如,这里是MAIN
。它的默认最小值为0,最大值为100,但是可以输入任何最小值和最大值。使用Guess the number (from Rosetta Code)可以在子例程中更改参数:
is copy
使用信息
此外,如果您的命令行参数与is copy
签名不匹配,则默认情况下会收到一条有用的用法消息。注意如何将以#!/bin/env perl6
multi MAIN
#= Guessing game (defaults: min=0 and max=100)
{
MAIN(0, 100)
}
multi MAIN ( $max )
#= Guessing game (min defaults to 0)
{
MAIN(0, $max)
}
multi MAIN
#= Guessing game
( $min is copy #= minimum of range of numbers to guess
, $max is copy #= maximum of range of numbers to guess
)
{
#swap min and max if min is lower
if $min > $max { ($min, $max) = ($max, $min) }
say "Think of a number between $min and $max and I'll guess it!";
while $min <= $max {
my $guess = (($max + $min)/2).floor;
given lc prompt "My guess is $guess. Is your number higher, lower or equal (or quit)? (h/l/e/q)" {
when /^e/ { say "I knew it!"; exit }
when /^h/ { $min = $guess + 1 }
when /^l/ { $max = $guess }
when /^q/ { say "quiting"; exit }
default { say "WHAT!?!?!" }
}
}
say "How can your number be both higher and lower than $max?!?!?";
}
开头的子例程和参数注释巧妙地合并到此用法消息中:
MAIN
这里
#=
不是定义的命令行参数,因此会触发此用法消息。
另请参见./guess --help
Usage:
./guess -- Guessing game (defaults: min=0 and max=100)
./guess <max> -- Guessing game (min defaults to 0)
./guess <min> <max> -- Guessing game
<min> minimum of range of numbers to guess
<max> maximum of range of numbers to guess
,--help
和2010上的Perl 6出现日历帖子,2014,2018和MAIN
。
或者,perl6也有一个Parsing command line arguments in Perl 6。您的程序几乎无需修改即可在其中运行: