使用 perl Getopt 惯用地处理重复的选项,如 -v -vv -vvv

Handle repeated options like -v -vv -vvv idiomatically with perl Getopt

我想像 OpenSSH 那样处理冗长级别选项:通过乘法传递 -v 选项。

Getopt::Std 不会递增无参数选项值,而只是将它们设置为 1。这意味着用 Getopt::Std 传递 -vvv 将产生 $opt_v == 1,在这种情况下我需要它是 3

Getopt::Long with the v+ option-spec 正确理解 -v -v(目标变量最终为 2),但它误解了 -vvv 作为选项named vvv -- 未定义并导致错误。

如何获得所需的行为?

我在写完问题后找到了答案,但在发布之前——经典。


处理此问题的最佳方法是使用 Getopt::Longbundling:

use Getopt::Long qw(:config bundling);
GetOptions ("v+" => $verbose);

这会按预期处理 -v -vv -vvv$verbose == 6


如果由于某种原因您不能使用或不想使用 bundling,唯一的其他方法是定义选项 vvvvv 等,直到合理的最大值:

use Getopt::Long;
GetOptions (
    "v+" => $verbose);
    "vv" => sub { $verbose += 2 },
    "vvv" => sub { $verbose += 3 },
);

这也会按预期处理 -v -vv -vvv$verbose == 6