问题描述
我有一个可否定的选项,定义为 top!。
当命令使用此选项时,请说:command_name -top,向用户打印警告
它的代码片段如下:
if ($args{top}) { print "Warning"; }
但是,当命令使用否定选项时,例如:command_name -notop,它不会向用户打印相同的警告。
有没有办法在这两种情况下获得相同的警告?
解决方法
是的,您可以确定您的选项(以任一形式)是否已在命令行上使用。 由于您对选项使用哈希,因此您可以检查选项 exists:
use warnings;
use strict;
use Getopt::Long qw(GetOptions);
my %args;
GetOptions(\%args,qw(top!));
print "Warning\n" if exists $args{top};
如果您在命令行上使用 Warning
或 -top
,这将打印 -notop
。如果您不使用 Warning
或 -top
,则不会打印 -notop
。