【发布时间】:2020-07-08 12:19:50
【问题描述】:
我有几个相互排斥的标志,女巫有自己的选择。可以说,如果我调用“stop_service”标志,我想要一个“name”选项;但如果我调用“send_report”标志,我想要一个“电子邮件”选项。对于解析,我使用“Getopt::Long”。这是代码:
use Getopt::Long;
# Option vars
my $stop_service; # flag
my $send_report; # flag
my $name; # string
my $email; # string
# Get all possible options
GetOptions(
# Flag and options for stop_service
"stop_service" => \$stop_service, # Mutual Exclusion Flag
"name=s" => \$name, # option string
# Flag and options for send_report
"send_report" => \$send_report, # Mutual Exclusion Flag
"email=s" => \$email, # option string
);
# Parsing correct combinations
# --stop_service --name XXX
if (($stop_service and !$send_report) # mutual exclusion
and ($name && !$email)) # options
{
print "stop_service + name: \n";
print $stop_service, " - ", $name, "\n";
}
# --send_report --email XXX
elsif ((!$stop_service and $send_report) # mutual exclusion
and (!$name && $email)) # options
{
print "send_report + email: \n";
print $send_report, " - ", $email, "\n";
}
# HELP
else {
print <<DOC;
Help in line 1.
Help in line 2.
DOC
}
效果很好:
[getopt]$ perl 06_getopt_cond_3.pl --stop_service --name jumersindo
stop_service + name:
1 - jumersindo
[getopt]$ perl 06_getopt_cond_3.pl --send_report --email jumer@jum.er
send_report + email:
1 - jumer@jum.er
[getopt]$ perl 06_getopt_cond_3.pl --send_report --name
Option name requires an argument
Help in line 1.
Help in line 2.
是否有更“自动”的配置方式?或者我需要用“if”语句指定所有选项组合?
【问题讨论】:
标签: perl args getopt-long