gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:57:39 27 4
gpt4 key购买 nike

我的目标是拥有一个 --override=f操作其他两个选项值的选项。诀窍是弄清楚如何在 f 中引用选项的值(与 =f 指示符中的 sub 匹配的部分)当 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]包含值。魔法。

我没有看到这个记录,所以我担心我是否在使用这种技术时无意中犯了任何错误。

最佳答案

来自 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 - 如何访问选项子中的 Getopt::Long 选项值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5281192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com