在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"
关联的值的数值类型约束产生类似的字符串类型的约束。
我该怎么做在Perl 6类似的东西?
这个功能是内置的Perl 6以下是用Perl 6的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
)。
:
前置到变量在子程序签名,使他们的名字命名(而不是位置)的参数。
使用$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
也可以与位置参数使用。例如,这里是Guess the number (from 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?!?!?";
}
此外,如果你的命令行参数不匹配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,2014和2018的Perl上MAIN
6发来临日历的帖子,帖子Parsing command line arguments in Perl 6和section of Synopsis 6 about MAIN。
另外,对于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;