在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;
Run Code Online (Sandbox Code Playgroud)
这里=i在"length=i"与关联的值上创建数字类型约束,--length并=s在其中"file=s"创建类似的字符串类型约束.
我如何在Perl 6中做类似的事情?
Chr*_*oms 16
该功能内置于Perl 6中.这相当于Getopt::LongPerl 6 中的代码:
sub MAIN ( Str :$file = "file.dat"
, Num :$length = Num(24)
, Bool :$verbose = False
)
{
$file.say;
$length.say;
$verbose.say;
}
Run Code Online (Sandbox Code Playgroud)
MAIN 是一个特殊的子例程,它根据其签名自动解析命令行参数.
Str并Num提供字符串和数字类型约束.
Bool制作$verbose二进制标志,False如果不存在或被称为--/verbose.(/in --/foo是用于设置参数的常见Unix命令行语法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;
}
Run Code Online (Sandbox Code Playgroud)
:x(:$smth)在此示例中--smth为短别名创建其他别名-x.多个别名和完全命名也是可用的,这里有一个例子::foo(:x(:bar(:y(:$baz))))将获得你--foo,-x和--bar,-y以及--baz它们中的任何一个将传递给$baz.
MAIN也可以与位置参数一起使用.例如,这里是猜数字(来自Rosetta Code).它默认为最小值0和最大值100,但可以输入任何最小值和最大值.使用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?!?!?";
}
Run Code Online (Sandbox Code Playgroud)
此外,如果命令行参数与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
Run Code Online (Sandbox Code Playgroud)
这--help不是定义的命令行参数,因此触发此使用消息.
另请参阅2010年,2014年和2018年 Perl 6出现日历帖子MAIN,Perl 6中的post Parsing命令行参数以及有关MAIN的概要6部分.
另外,perl6 也有一个Getopt::Long。您的程序几乎无需修改即可在其中运行:
use Getopt::Long;
my $data = "file.dat";
my $length = 24;
my $verbose;
get-options("length=i" => $length, # numeric
"file=s" => $data, # string
"verbose" => $verbose); # flag
say $length;
say $data;
say $verbose;
Run Code Online (Sandbox Code Playgroud)