我写了以下代码:
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
或--help
调用脚本,它也不会调用子例程。我哪里错了?
如果我按如下方式更改代码,它总是在没有任何命令行参数的情况下调用第一个子例程:
my $ret = GetOptions ( "version" => &$version,
"h|help" => &$usage );
答案 0 :(得分:7)
\$version
是对$version
的引用,其中$version
是对匿名子程序的引用;所以,\$version
是对子程序的引用的引用。这太间接了。你只需要一个参考水平:
my $ret = GetOptions ( "version" => $version,
"h|help" => $usage );