Questions about this topic? Sign up to ask in the talk tab.
Difference between revisions of "Perl/Basics/User Input/Command Line/Getopt::Long"
From NetSec
AlizaLorenzo (Talk | contribs) (Created page with "This requires Getopt::Long. The perldoc is [http://perldoc.perl.org/Getopt/Long.html here].") |
Chantal21I (Talk | contribs) |
||
Line 1: | Line 1: | ||
This requires Getopt::Long. The perldoc is [http://perldoc.perl.org/Getopt/Long.html here]. | This requires Getopt::Long. The perldoc is [http://perldoc.perl.org/Getopt/Long.html here]. | ||
+ | =====Code===== | ||
+ | {{:Perl/Basics/User_Input/Command_Line/Getopt::Long/Code}} | ||
+ | =====Analysis===== | ||
+ | {{:Perl/Basics/User_Input/Command_Line/Getopt::Long/Analysis}} |
Latest revision as of 01:38, 19 July 2012
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.