[0] # cat parameter_check.pl
use v5.10;
use warnings;
use strict 'subs';
use feature 'state';
use Getopt::Std;
getopts("b:cd:",\%options);
if( exists $options{'b'} ){
if( $options{'b'} ){
say "option b $options{'b'}";
}else{
say "b is zero length string or equvalent";
}
}else{
say 'key b does not exist';
}
say "option c:", $options{'c'};
say "option d: ", $options{'d'};
####
parameter_check.pl -b -ddd
####
parameter_check.pl -ddd -b
####
[0] # perl parameter_check.pl -ddd -c -b
b is zero length string or equivalent
option c:1
option d: dd
[0] # perl parameter_check.pl -ddd -b -c
option b: -c
Use of uninitialized value in say at parameter_check.pl line 18.
option c:
option d: dd
[0] # perl parameter_check.pl -ddd -b -c
option b -c
Use of uninitialized value in say at parameter_check.pl line 18.
option c:
option d: dd
[0] # perl parameter_check.pl -ddd -c -b --
option b --
option c:1
option d: dd
[0] # perl parameter_check.pl -c -b -ddd
option b -ddd
option c:1
Use of uninitialized value in say at parameter_check.pl line 19.
option d:
####
sub getopts ($;$) {
my ($argumentative, $hash) = @_;
my (@args,$first,$rest,$exit);
my $errs = 0;
local $_;
local @EXPORT;
@args = split( / */, $argumentative );
while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/s) {
($first,$rest) = ($1,$2);
if (/^--$/) { # early exit if --
shift @ARGV;
last;
}
my $pos = index($argumentative,$first);
if ($pos >= 0) {
if (defined($args[$pos+1]) and ($args[$pos+1] eq ':')) {
shift(@ARGV);
if ($rest eq '') {
++$errs unless @ARGV;
$rest = shift(@ARGV);
}
if (ref $hash) {
$$hash{$first} = $rest;
}
else {
${"opt_$first"} = $rest;
push( @EXPORT, "\$opt_$first" );
}
}
else {
if (ref $hash) {
$$hash{$first} = 1;
}
else {
${"opt_$first"} = 1;
push( @EXPORT, "\$opt_$first" );
}
if ($rest eq '') {
shift(@ARGV);
}
else {
$ARGV[0] = "-$rest";
}
}
}
else {
if ($first eq '-' and $rest eq 'help') {
version_mess($argumentative, 'main');
help_mess($argumentative, 'main');
try_exit();
shift(@ARGV);
next;
} elsif ($first eq '-' and $rest eq 'version') {
version_mess($argumentative, 'main');
try_exit();
shift(@ARGV);
next;
}
warn "Unknown option: $first\n";
++$errs;
if ($rest ne '') {
$ARGV[0] = "-$rest";
}
else {
shift(@ARGV);
}
}