2

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Jay Gridley
  • 713
  • 2
  • 12
  • 33
  • 4
    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 Mar 16 '10 at 15:18
  • 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 Mar 16 '10 at 15:30
  • 4
    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 Mar 16 '10 at 15:44

3 Answers3

6

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
toolic
  • 57,801
  • 17
  • 75
  • 117
3

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.

DVK
  • 126,886
  • 32
  • 213
  • 327
0
#!/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?

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339