在 Perl 中使用 Getopt 时如何对参数进行分组?
对于我正在编写的 Perl 脚本,可能会提供很多(~50)个命令行选项。其中大多数都是可选的,因此调用时只会提供部分选项。
我正在使用 Getopt::Long
但它不允许我多次使用 GetOptions
。因此,我必须在一次 GetOptions
调用中使用所有命令行选项。
使用GetOptions
时是否有一些好的方法来对选项进行分组?
$ cat test.pl
use strict;
use warnings;
use Getopt::Long;
my ($a, $b, $c, $d);
GetOptions ('a=s' => \$a, 'b=s' => \$b);
GetOptions ('c=s' => \$c, 'd=s' => \$d);
print "a = $a\nb = $b\nc = $c\nd = $d\n";
$ perl test.pl -a=AA -b=BB -c=CC -d=DD
Unknown option: c
Unknown option: d
Use of uninitialized value in concatenation (.) or string at test.pl line 10.
Use of uninitialized value in concatenation (.) or string at test.pl line 10.
a = AA
b = BB
c =
d =
$
To a perl script that I am writing, there can be a lot (~50) of command line options provided. Most of them are optional, so a call will have only some of the options provided.
I am using Getopt::Long
but it does not allow me to use GetOptions
more than once. As a result, I have to use all the command line options in one GetOptions
call.
Is there some good way to group the options while using GetOptions
?
$ cat test.pl
use strict;
use warnings;
use Getopt::Long;
my ($a, $b, $c, $d);
GetOptions ('a=s' => \$a, 'b=s' => \$b);
GetOptions ('c=s' => \$c, 'd=s' => \$d);
print "a = $a\nb = $b\nc = $c\nd = $d\n";
$ perl test.pl -a=AA -b=BB -c=CC -d=DD
Unknown option: c
Unknown option: d
Use of uninitialized value in concatenation (.) or string at test.pl line 10.
Use of uninitialized value in concatenation (.) or string at test.pl line 10.
a = AA
b = BB
c =
d =
$
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将选项存储在散列中可能是个好主意:
请参阅
Getopt: :Long
:将选项值存储在哈希中 :It may be a good idea to store your options in a hash instead:
See
Getopt::Long
: Storing options values in a hash :最直接的答案是使用 Getopt::Long::Configure,如下所示:
请注意,您应该确保最后一次调用 GetOptions 应配置为 no_pass_through,以确保收到有关未知的警告选项。
The most direct answer is to use Getopt::Long::Configure like so:
Note that you should make sure that your last invocation of GetOptions should be configured with no_pass_through to make sure that you get warnings about unknown options.
有什么问题:
或者,如果它们都很短,您可以这样做:(
请注意,将
$a
和$b
用于除之外的任何内容都是一个坏主意>排序
比较。)What's wrong with:
Or, if they're all short, you could do:
(Note that it's a bad idea to use
$a
and$b
for anything exceptsort
comparisions.)通常,数组在传递给函数之前会被展平为单个列表,尽管有些函数会覆盖此行为。使用它,您可以定义选项组数组并将数组列表传递给 GetOptions。
您可以将其与在散列中存储值结合起来,以避免创建大量选项变量,如 Zaid 提到的。
Normally arrays are flattened out into a single list before being passed to a function, although some functions override this behavior. Using this you can define arrays of option groups and pass the list of arrays to GetOptions.
You can combine this with storing values in a hash to prevent having to create a huge number of option variables as Zaid mentioned.