Perl getopts Howto

This how-to comes with no guaratees other than the fact that these code segments were copy/pasted from code that I wrote and ran successfully.

Process options passed to a program using getopts().

Make a global hash to store the options. Use the standard Getopt module. Make a string of one-character options. A character preceeding a colon takes an argument. The getopts function takes two arguments: a string of options, and a hash reference. For each command line option (aka switch) found, getopts sets $opt{x} (where x is the switch name) to the value of the argument, or 1 if no argument was provided.

Example

    #
    # Globals
    #
    use vars qw/ %opt /;
    #
    # Command line options processing
    #
    sub init()
    {
        use Getopt::Std;
        my $opt_string = 'hvdf:';
        getopts( "$opt_string", \%opt ) or usage();
        usage() if $opt{h};
    }
    #
    # Message about this program and how to use it
    #
    sub usage()
    {
        print STDERR << "EOF";
    This program does...
    usage: $0 [-hvd] [-f file]
     -h        : this (help) message
     -v        : verbose output
     -d        : print debugging messages to stderr
     -f file   : file containing usersnames, one per line
    example: $0 -v -d -f file
    EOF
        exit;
    }
    init();
    print STDERR "Verbose mode ON.\n" if $opt{v};
    print STDERR "Debugging mode ON.\n" if $opt{d};


AUTHOR

Alex BATKO <abatko AT cs.mcgill.ca>

Thanks to all those who have written with suggestions and comments.


DONATE

Hi! If this document helped you figure out something you were stuck on; if it saved you time; if it relieved some frustration or anxiety... please consider donating. Thank you kindly!


SEE ALSO

http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/

http://alex.exitloop.ca/abatko/computers/programming/perl/howto/