Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one respond to the --help flag with Getopt::Std?

Tags:

perl

getopt

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.

like image 670
Daniel Avatar asked Feb 22 '14 15:02

Daniel


1 Answers

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
like image 81
Lee Duhem Avatar answered Oct 11 '22 16:10

Lee Duhem