Getopt :: Long和anonymous子例程

时间:2012-10-09 21:17:47

标签: 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 " --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 );

1 个答案:

答案 0 :(得分:7)

\$version是对$version的引用,其中$version是对匿名子程序的引用;所以,\$version是对子程序的引用的引用。这太间接了。你只需要一个参考水平:

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