Getopt::Long can be used to parse options that are passed to a perl script.
use strict;
use warnings;
use Getopt::Long;
use vars qw($opt);
$opt = { "help" => \&Usage, };
Getopt::Long::GetOptions(
$opt,
"help",
"flag_1=s",
"other_flag=s",
);
print("\n");
for my $option_given (qw{flag_1 other_flag}) {
if (exists $opt->{$option_given}) {
printf("Option %-10s: %s\n", $option_given, $opt->{$option_given} );
}
}
print("\n");
sub Usage {
print STDERR <<"USAGE";
Usage: perl $0 [options]
Possible options are:
--help This help message
--flag_1=<a flag> Use <a flags> for the flag you want
to specify.
--other_flag=<other> Use <other> as you may wish.
USAGE
}
#
# default_value.pl
# default_value.pl --override OVR
#
use strict;
use warnings;
use Getopt::Long;
my $default_value='DEF';
my $override = $default_value;
# The equal sign between override and s indicates that the option requires a value (if
# the option IS used). Compare with ./optional_value.pl
GetOptions('override=s' => \$override);
print "\n";
if ($override eq $default_value) {
print "Value was not overridden, use --override if needed\n";
}
else {
print "Default value overridden with $override\n";
}
#!/usr/bin/perl
#
# The most simple options are the ones that take no values, that is: flags
#
use strict;
use warnings;
use Getopt::Long;
my $flag_1 = ''; # turn flag on with --flag_1
my $flag_2 = ''; # turn flag on with --flag_2
GetOptions('flag_1' => \$flag_1, 'flag_2' => \$flag_2);
print "The following flags were set:\n";
print "flag_1: " . ($flag_1 ? "yes" : "no") . "\n";
print "flag_2: " . ($flag_2 ? "yes" : "no") . "\n";
#
# ./optional_value.pl
# ./optional_value.pl --opt
# ./optional_value.pl --opt some_value
#
use warnings;
use strict;
use Getopt::Long;
my $opt;
# The colon sign between opt and s indicates that an optional value
# can be passd after --opt. Compare with ./default_value.pl
GetOptions('opt:s' => \$opt);
print "\n";
if (defined $opt) {
if ($opt) {
print "The --opt flag was used and the optional value $opt was given\n";
}
else {
print "The --opt flag was used, yet without specifing a value\n";
}
}
else {
print "The --opt flag was not used\n";
}
#
# Call with
#
# -a
# -ab
# -abc
# ....
# -abcdefgh
#
# or
#
# -x
#
# or
#
# without option at all
#
use warnings;
use strict;
use Getopt::Long;
GetOptions (
'x|abcdefgh' => \my $abcdefgh
);
if ($abcdefgh) {
print "You have used either -x or -abcdefgh\n";
}
else {
print "You chose neither -x or -abcdefgh\n";
}
# hash_values.pl --translation one=eins --translation two=zwei
use strict;
use warnings;
use Getopt::Long;
my %translations = ();
GetOptions('translation=s%' => \%translations);
for my $english_word (keys %translations) {
print "$english_word was translated into $translations{$english_word}\n";
}
#
# http://stackoverflow.com/questions/27645166/getoptlong-with-special-character-options-such-as
#
use warnings;
use strict;
use Getopt::Long;
my $percent = 100;
die unless GetOptions (
'percent|%=f' => \$percent
);
print "\n $percent%\n\n";