Zagorax
Zagorax

Reputation: 11890

Getopt::Long and anonymous subroutine

I've written the following code:

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 );

But also if I call the script with --version or --help it doesn't call the subroutine. Where am I wrong?

And if I change the code as follows, it always call the first subroutine also without any command line parameter:

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

Upvotes: 2

Views: 223

Answers (1)

ruakh
ruakh

Reputation: 183290

\$version is a reference to $version, where $version is a reference to an anonymous subroutine; so, \$version is a reference to a reference to a subroutine. That's too much indirection. You just need a single level of reference-ness:

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

Upvotes: 7

Related Questions