perl – 如何在选项的子中访问Getopt :: Long选项的值?

我的目标是使用–override = f选项来操纵其他两个选项的值.诀窍是弄清楚如何在GetOptions检测到命令行上存在选项时执行的子中引用选项的值(与= f指示符中的f匹配的部分).


use strict;
use warnings;
use Getopt::Long;
our %Opt = (
    a   => 0,
    b   => 0,
our %Options = (
    "a=f"       => \$Opt{a},
    "b=f"       => \$Opt{b},
    "override=f"    => sub { $Opt{$_} = $_[1] for qw(a b); },  # $_[1] is the "trick"
GetOptions(%Options) or die "whatever";
print "\$Opt{$_}='$Opt{$_}'\n" for keys %Opt;

$ --override=5

$ --a=1 --b=2 --override=5 --a=3

代码似乎像我想要的那样处理选项和覆盖.我发现在sub中,$_ [0]包含选项的名称(全名,即使它在命令行中缩写),$_ [1]包含该值.魔法.


fine manual

When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option. (Actually, it is an object that stringifies to the name of the option.) For a scalar or array destination, the second argument is the value to be stored. For a hash destination, the second arguments is the key to the hash, and the third argument the value to be stored.