Reputation: 49
My program is as follows:
use strict;
use warnings;
use Getopt::Long;
my @letters;
my @words;
GetOptions(
"letters=s{2}" => \@letters,
"words=s{,}" => \@words
);
print "Letters: " . join(", ", @letters) . "\n";
print "Words: " . join(", ", @words) . "\n";
When I run this program I get the output as follows:
perl getopts.pl --letters a --words he she it
Letters: a, --words
Words:
--words
is read as part of --letters
arguments itself. I expect GetOptions
to throw error message in this scenario. How to get this done.
Upvotes: 0
Views: 237
Reputation: 29854
A quantifier of '{2}'
means "exactly two". So, it's even ignoring the second argument afterwards is a switch.
The GetOpt::Long text that you probably took this from:
GetOptions( 'coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color );
Are specific conditions for which pairs and triads make sense. You want an x and a y coordinate, or you want a value for each part of an RGB specification. Just the way that you would expect 'cmykcolor={4}'
.
If you want at least one, up to the next switch, you can specify '{1,}'
as your quantifier, and if you want "at most two", then '{1,2}'
makes sense. Interestingly enough, the behavior of '{,2}'
is exactly the same as '{1,2}'
. It seems that as long as you specify a quantifier, it will suck up one more argument, regardless of whether or not the next argument is a switch.
So the quantifiers in Getopt::Long
may look the same as regex, but they mean different things.
Upvotes: 2
Reputation: 7516
Change:
"letters=s{2}" => \@letters,
to:
"letters=s{1,2}" => \@letters,
...which allows 1-to-2 letters as the argument.
Upvotes: 6