如何使用 Getopt::Long[::Descriptive] 处理由任意数字组成的选项?

How can I handle an option made of an arbitrary number with Getopt::Long[::Descriptive]?

我希望能够像 head-tail 那样处理 -1-10 等选项。

也就是说,能够做到

my_script.pl -10 --some-other-option arguments

并能够保留 -10 选项的值。

现在唯一可行的想法是在 之前处理命令行 它被馈送到 describe_options 像这样:

my ($count) = map { /\-(\d+)/;  } grep { /^\-(\d+)$/ } reverse @ARGV;
@ARGV = grep { !/^\-\d+$/ } @ARGV;

my ($opt, $usage) = describe_options(...)

但它看起来很笨重,而且 $usage 中没有弹出该选项。

有没有更好的方法?使用 Getopt::Long 的答案也可以 - 我可以将它们调整为 GetOpt::Long::Descriptive

Getopt::Long(不确定 Getopt::Long::Descriptive)可以配置为在未知参数上调用用户提供的函数;这可以用来处理这种情况。

示例:

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
# :config required to enable handling of "<>" psuedo-option
use Getopt::Long qw/:config pass_through/;
use Scalar::Util qw/looks_like_number/;

my $verbose = 0;
my $lines = 10;
GetOptions("verbose" => $verbose,
           "<>" => \&parse_lines)
    or die "Unable to parse options.\n";
say "Lines is $lines";

sub parse_lines {
    my $arg = shift;
    if (looks_like_number $arg) {        
        $lines = $arg =~ s/^-//r; # Turn -X into X
    } else {
        die "Invalid option '$arg'\n";
    }
}

和用法:

$ perl foo.pl -123
Lines is 123
$ perl foo.pl --bar
Invalid option '--bar'
Unable to parse options.