start page | rating of books | rating of authors | reviews | copyrights

Book Home Programming PerlSearch this book

32.28. Getopt::Std

use Getopt::Std;
You can use getopt and getopts with globals:
our ($opt_o, $opt_i, $opt_f);
getopt('oif');            # -o, -i, and -f all take arguments.
                          # Sets global $opt_* variables.
getopts('oif:');          # Now -o & -i are boolean; -f takes an arg.
                          # Still sets global $opt_* as side effect.
Or you can use them with a private options hash:
my %opts;                 # We'll place results here.
getopt('oif', \%opts);    # All three still take arguments.
getopts('oif:', \%opts);  # Now -o and -i are boolean flags
                          # and only -f takes an argument.
The Getopt::Std module provides two functions, getopt and getopts, to help you parse command-line arguments for single-character options. Of the two, getopts is the more useful because it lets you specify that some options take arguments and others don't, whereas getopt assumes all options take arguments. By specifying to getopts a letter with a colon after it, you indicate that that argument takes an argument; otherwise, a Boolean flag is expected. Standard option clustering is supported. Ordering doesn't matter, so options taking no arguments may be grouped together. Options that do take an argument must be the last in a group or by themselves, and their argument may either come immediately after the option in the same string, or else as the next program argument. Given the example getopts use above, these are equivalent calls:
% prog -o -i -f TMPFILE more args here
% prog -o -if TMPFILE more args here
% prog -io -fTMPFILE more args here
% prog -iofTMPFILE more args here
% prog -oifTMPFILE more args here



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.