The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.


Getopt::WonderBra - Lift and Separate Command Line Options


        use Getopt::WonderBra;
        @ARGV = getopt( 'opts:-:', @ARGV );

        sub help() { print "Useless help message"; };
        sub version() { print "Useless version message"; };
        while ( ( $_ = shift ) ne '--' ) {
                if    (/^-o$/) { $opt_o++ }
                elsif (/^-p$/) { $opt_p++ }
                elsif (/^-t$/) { $opt_t++ }
                elsif (/^-s$/) { push( @opt_s, shift ); }
                elsif (/^--/)  { push( @opt_long, $_ ); }
                else           { die 'I do not grok -', $_; }
        print "-o given $opt_o times" if $opt_o;
        print "-p given $opt_p times" if $opt_p;
        print "-t given $opt_t times" if $opt_t;
        print "-s given with arg $_" for @opt_s;
        print "long opt $_ given" for @opt_long;
        print "";
        print "  param: $_" for @ARGV;


perl5.008006, Carp, Exporter




See eg/ for an example of usage.

There just weren't enough command line processessing modules, so I had to write my own. Actually, it exists because it made it easy to port shell scripts to perl: it acts just like the getopt program. Oddly, none of the modules that are actually named after it do. (Though some act like the C function) The following sequence chops your args up and gives 'em to you straight:


main::help() must exist prior to calling getopt(). It is wrapped by this module. This is done to ensure correct behavior for programs that use getopt. (e.g. error messages to stdout if --help in specified, so $ foo --help | less has the desired results)

main::help() is replaced by a wrapper that will exit the program. If it gets args, it will select STDERR, call your help function, print the passed args, and exit non-zero.

Otherwise, it will select STDOUT, call your help function, and exit non-zero.

Note that the program will exit if you call help after calling getopt, as well. This is not a bug. It's for issuing error messages while handling the parsed args.

The wrapper sub never returns.


If you define a main::version() sub, it will be called if the user specified --version, and the program will terminate.

STDOUT will always be selected.