Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata