首页 > 解决方案 > perl 中的可否定选项

问题描述

我有一个否定选项定义为顶部!.

当命令使用此选项时,例如:command_name -top,向用户打印警告

它的代码片段如下:

if ($args{top}) { print "Warning"; }

但是,当命令使用否定选项时,例如:command_name -notop,它不会向用户打印相同的警告。

有没有办法为这两种情况获得相同的警告?

标签: perlcommand-line-argumentsoptionsgetoptgetopt-long

解决方案


是的,您可以确定您的选项(以任何一种形式)是否已在命令行上使用。由于您为选项使用哈希,因此您可以检查选项是否存在

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


推荐阅读