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

前端之家收集整理的这篇文章主要介绍了perl – 如何在选项的子中访问Getopt :: Long选项的值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的目标是使用–override = f选项来操纵其他两个选项的值.诀窍是弄清楚如何在GetOptions检测到命令行上存在选项时执行的子中引用选项的值(与= f指示符中的f匹配的部分).

我是这样做的:

$cat t.pl
#!/usr/bin/perl
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;

$t.pl --override=5
$Opt{a}='5'
$Opt{b}='5'

$t.pl --a=1 --b=2 --override=5 --a=3
$Opt{a}='3'
$Opt{b}='5'

代码似乎像我想要的那样处理选项和覆盖.我发现在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.

因此,您所看到的行为会被记录下来,您应该对此保持安全.

猜你在找的Perl相关文章