Perl getopts Howto--如何使用perl中的getopts

Perl getopts Howto

This howto 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>

你可能感兴趣的:(String,File,command,perl,processing,debugging)