Perl:使用GetOptions过滤无效参数
我正在 Perl 中编写一个小脚本,但我在使用命令行参数时遇到问题。我使用 GetOps 来解析它们,如下面的代码所示:
%params = (
"help" => "",
"no_inline" => "",
"no_dupl" => ""
);
¶mError if (!GetOptions(
"help" => \$params{"help"},
"no-inline" => \$params{"no_inline"},
"no-duplicates" => \$params{"no_dupl"},
));
然后我像这样运行脚本:
> script.pl --no-inline # ok, valid parameter
> script.pl --no-inline blahblah # blahblah is not valid
> script.pl --no-i # not valid
问题是在第二个和第三个示例中 GetOps 表示参数有效。我应该怎么做才能使这些参数无效?
I'm working on a little script in Perl and I have problems with parameters from the command line. I'm using GetOps to parse them as shown in the code below:
%params = (
"help" => "",
"no_inline" => "",
"no_dupl" => ""
);
¶mError if (!GetOptions(
"help" => \$params{"help"},
"no-inline" => \$params{"no_inline"},
"no-duplicates" => \$params{"no_dupl"},
));
I then run the script like this:
> script.pl --no-inline # ok, valid parameter
> script.pl --no-inline blahblah # blahblah is not valid
> script.pl --no-i # not valid
Problem is that in the second and third example GetOps says the parameters are valid. What should I do in order do make these parameters invalid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的第三个例子是有效的。
GetOptions
接受缩写名称,只要它们不模糊即可。例如,如果您有一个名为
no-indent
的选项,则您的第三个示例将被拒绝,因为它不明确,但--no-inl
仍会被接受。要禁用此功能,请使用:
请参阅配置 Getopt::Long 其他选项。
你的第二个例子是完全正常的。
blahblah
将在GetOptions
调用后保留在@ARGV
中。如果您的脚本仅接受您指定的选项,并且不能采用其他参数(例如文件名或其他参数),则只需在调用后检查@ARGV
是否为空。Your third example is valid.
GetOptions
accepts abbreviated names as long as they are not ambiguous.If you had for example an option called
no-indent
, your third example would have been rejected because it is ambiguous, but--no-inl
would still be accepted.To disable this, use:
See Configuring Getopt::Long for other options.
Your second example is perfectly normal.
blahblah
will be left in@ARGV
after theGetOptions
call. If your script only accepts the options you specified, and cannot take other arguments (like filenames or whatever), just check that@ARGV
is empty after the call.