Pergunta

I want my script to print a help message when it is run with the --help command line option. Based on the Getopt::Std documentation, this sub should do the trick:

#!/usr/bin/env perl
use strict;
use warnings;
use 5.014;
use Getopt::Std;

sub HELP_MESSAGE {
    say "HELP MESSAGE";
}

But it prints nothing. I also tried adding this, out of curiosity:

for (@ARGV) {
    HELP_MESSAGE() if /--help/;
}

It actually works, but seems rather sloppy. I know using the -h flag would be quite simple, but I would like to have both.

Foi útil?

Solução

The documentation of Getopt::Std says

If - is not a recognized switch letter, getopts() supports arguments --help and --version. If main::HELP_MESSAGE() and/or main::VERSION_MESSAGE() are defined, they are called; ...

So try this:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.014;
use Getopt::Std;

$Getopt::Std::STANDARD_HELP_VERSION = 1;
our $VERSION = 0.1;

getopts('');       # <<< You forgot this line, and `getopt()` DOES NOT work

sub HELP_MESSAGE {
    say "HELP MESSAGE";
}

Test run:

$ ./t00.pl --help
./t00.pl version 0.1 calling Getopt::Std::getopts (version 1.07),
running under Perl version 5.16.3.
HELP MESSAGE
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top