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

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

From NetSec
Jump to: navigation, search

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

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;

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

 perl --message "hello" --boolean
 perl --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.