Questions about this topic? Sign up to ask in the talk tab.

Perl/Basics/User Input/Command Line/Getopt::Long

From NetSec
Revision as of 02:38, 19 July 2012 by Chantal21I (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This requires Getopt::Long. The perldoc is here.

Code
 
use strict;
use warnings;
use Getopt::Long;
 
my $message, $boolean;
GetOptions('message=s' => \$message, 'boolean' => \$boolean);
 
print $message . "\n";
print "The boolean -b option was set!\n" if defined $boolean;
print "The boolean -b option was not set!\n" if undef $boolean;
 
Analysis

The GetOptions() function receives message formats and references for variable assignment. You can execute the script as follows:

 perl script.pl --message "hello" --boolean
 perl script.pl --message "hello"

In the above example, we see the line:

 GetOptions('message=s' => \$message, 'boolean' => \$boolean);

You can see from the execution pattern above that the GetOptions() function provides an interface for the "double-dash" style command line arguments. The GetOptions() function receives a hash. The =s after message designates that the --message parameter receives a string data type. An =i will change it to integer. Simple no = will set the flag to a boolean; similar to an argument without a colon in Getopt::Std. Notice each variable is passed as a reference.