如何在选项的子项中访问 Getopt::Long 选项的值?
我的目标是有一个 --override=f
选项来操纵其他两个选项的值。诀窍是弄清楚如何在执行的 sub
中引用选项的值(与 =f
指示符中的 f
匹配的部分)当 GetOptions 检测到命令行上存在该选项时。
我的做法如下:
$ 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]
包含该值。魔法。
我还没有看到这个记录,所以我担心我是否在使用这种技术时无意中犯了任何错误。
My goal is to have a --override=f
option that manipulates the values of two other options. The trick is figuring out how to refer to the option's value (the part matching the f
in the =f
designator) in the sub
that's executed when GetOptions detects the presence of the option on the command line.
Here is how I'm doing it:
$ 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'
The code appears to handle options and overrides just like I want. I have discovered that within the sub
, $_[0]
contains the name of the option (the full name, even if it's abbreviated on the command line), and $_[1]
contains the value. Magic.
I haven't seen this documented, so I'm concerned about whether I'm unwittingly making any mistakes using this technique.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自精细手册:
因此,您所看到的行为已被记录下来,您应该放心使用它。
From the fine manual:
So, the behavior that you're seeing is documented and you should be safe with it.