perl 中的否定选项

Negatable options in perl

我有一个可否定选项定义为 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};

如果您在命令行中使用 -top-notop,这将打印 Warning。如果您不使用 -top-notop.

,它不会打印 Warning