2
votes

I am parsing command line options in Perl using Getopt::Long. I am forced to use prefix - (one dash) for short commands (-s) and -- (double dash) for long commands (e.g., --input=file).

My problem is that there is one special option (-r=<pattern>) so it is long option for its requirement for argument, but it has to have one dash (-) prefix not double dash (--) like other long options. Is possible to setup Getopt::Long to accept these?

3
Ouch. It really can't be changed to -r arg or --r=arg or anything at this point? Not only is it making work for you, seems like it's confusing to the user to have an option breaking the usual convention. - Cascabel
P.S. I'm not trying to avoid giving you an answer - I know you're probably already aware of what I said. (Also I don't think there is an answer within Getopt::Long) - Cascabel
The trick is to make arguments look like what people expect from other programs. It's when you want a new syntax that things get weird and you have to do a lot of work to parse them. - brian d foy

3 Answers

6
votes

By default, Getopt::Long interchangeably accepts either single (-) or double dash (--). So, you can just use --r=foo. Do you get any error when you try that?

use strict;
use warnings;
use Getopt::Long;
my $input = 2;
my $s = 0;
my $r = 3;
GetOptions(
    'input=s' => \$input,
    's'       => \$s,
    'r=s'     => \$r,
);
print "input=$input\n";
print "s=$s\n";
print "r=$r\n";

These sample command lines produce the same results:

my_program.pl --r=5
my_program.pl --r 5
my_program.pl  -r=5
my_program.pl  -r 5

input=2
s=0
r=5
3
votes

Are you setting "bundling" on?

If so, you can disable bundling (but then, you won't be able to do things like use myprog -abc instead of myprog -a -b -c).

Otherwise, the only thing that comes to mind right now is to use Argument Callback (<>) and manually parse that option.

0
votes
#!/usr/bin/perl

use strict; use warnings;

use Getopt::Long;

my $pattern;

GetOptions('r=s' => \$pattern);

print $pattern, "\n";

Output:

C:\Temp> zz -r=/test/
/test/
C:\Temp> zz -r /test/
/test/

Am I missing something?