加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 06:18:08 所属栏目:大数据 来源:网络整理
导读:我的目标是使用–override = f选项来操纵其他两个选项的值.诀窍是弄清楚如何在GetOptions检测到命令行上存在选项时执行的子中引用选项的值(与= f指示符中的f匹配的部分). 我是这样做的: $cat t.pl#!/usr/bin/perluse strict;use warnings;use 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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读