Home arrow Perl Programming arrow Page 4 - Processing Command Line Options with PERL

GetOptions() Function - Perl

Over the course of the next few pages, I will introduce you to one of the more interesting modules in the Perl pantheon, the Getopt::Long.pm module. This module provides a simple API to parse options passed to your Perl scripts at the command line and convert them into Perl scalars or arrays.

  1. Processing Command Line Options with PERL
  2. The POSIX Standard
  3. Down To Work
  4. GetOptions() Function
  5. Half-Life
  6. Getopt::Long.pm
  7. Opting In
  8. Negative Reinforcement
  9. Hashing It Up
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 58
March 31, 2004

print this article



Most of the magic here lies in the call to the GetOptions() function. This function accepts a series of option-variable pairs, demarcated using standard hash notation and separated with commas. When GetOptions() is called, it reads the program command line, looks for matching arguments, and if found, sets the corresponding option variable to true. Thus when you call the Perl script above with the "--debug" option, GetOptions() recognizes it and automatically sets the $debug variable to true.

You can set more than one option variable at a time as well. Consider the following example and its output, which demonstrates:

# import module
use Getopt::Long;
# read options
$result = GetOptions ( "red" => $red,
    "blue" => $blue,
    "green" => $green );  

# print options
$red ? print "Red is presentn" : print "Red is absentn"; $blue ? print
"Blue is presentn" : print "Blue is absentn"; $green ? print "Green is
presentn" : print "Green is absentn"; 

Here's an example of the output:

$ ./colors.pl  --red --blue
Red is present
Blue is present
Green is absent

>>> More Perl Programming Articles          >>> More By icarus, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: