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.


    # 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
    print STDERR "Verbose mode ON.\n" if $opt{v};
    print STDERR "Debugging mode ON.\n" if $opt{d};


Alex BATKO <abatko AT>

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


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!