Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl Getopt::长的匿名子例程_Perl - Fatal编程技术网

Perl Getopt::长的匿名子例程

Perl Getopt::长的匿名子例程,perl,Perl,我编写了以下代码: my $version = sub { print "$PROGNAME $VERSION - $AUTHOR\n"; exit 0; }; my $usage = sub { print "Usage: proll <options>\n"; print "Available options:\n"; print " -h, --help Print this help and exit.\n"; print

我编写了以下代码:

my $version = sub {
    print "$PROGNAME $VERSION - $AUTHOR\n";
    exit 0;
};

my $usage = sub {
    print "Usage: proll <options>\n";
    print "Available options:\n";
    print " -h, --help  Print this help and exit.\n";
    print " --version   Print version.\n";
    print " XdY     Launch X dice with Y faces.\n";
    exit 0;
};

my $ret = GetOptions ( "version" => \$version,
                       "h|help" => \$usage );

\$version
是对
$version
的引用,其中
$version
是对匿名子例程的引用;所以,
\$version
是对子程序的引用。那太间接了。您只需要一个参考级别:

my $ret = GetOptions ( "version" => $version,
                       "h|help" => $usage );

或者,如果它是一个非常短的子例程,只需要根据命令行上传递的选项调用它,那么您可以简单地使用一个匿名子例程:
GetOptions(“dostuff”=>sub{[do stuff here]})。这对于一次设置多个变量或以特殊方式实例化对象非常有用。非常感谢,它很有效。只想知道:如果它需要引用,为什么它在找到结尾之前不跟随引用“流”?@Zagorax:
GetOptions
有一些不同的调用约定(请参阅)。使用它的一种方法是使用它的方式,如果选项存在,则传入对子例程的引用以调用,但另一种方法是传入对标量的引用,如果选项存在,则该标量应设置为选项的值。由于引用是一种标量类型,
\$version
触发后一种调用约定,因此
GetOptions
认为需要将
--version
的值存储在变量
$version
中。
my $ret = GetOptions ( "version" => $version,
                       "h|help" => $usage );