开发者

How can I handle -r=<pattern> with Perl's Getopt::Long?

开发者 https://www.devze.com 2022-12-23 06:06 出处:网络
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).

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 fo开发者_如何学Pythonr 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?


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


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.


#!/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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号