如何使用 ARGV 传递命令行标志,同时为标志指定特定顺序?
我想将 ARGV 的使用集成到我的脚本中。在弄乱了我在 Stack Overflow 上找到的一个简单用法的示例后,我能够使脚本“强制”使用单个命令参数。我现在想要的是允许多个标志而不是只有一个。问题是如果使用多个标志,则需要按特定顺序强制执行。
这是我为执行单个参数并强制执行它而提出的代码。
#!/usr/bin/perl
use strict;
use warnings;
system ("clear");
print "Solignis's Discovery Script v0.6 for ESX\\ESX(i) 4.0+\n\n";
my $numargs = $#ARGV + 1;
if ($#ARGV < 0) {
help_menu();
}
foreach my $argval (0 .. $#ARGV) {
if (($#ARGV == 0) && ($ARGV[0] eq '-b')) {
print "Backup\n";
} elsif (($#ARGV == 0) && ($ARGV[0] eq '-d')) {
print "Discovery\n";
} elsif ((($#ARGV == 0) && ($ARGV[0] eq '-h') || ($#ARGV == 0) && ($ARGV[0] eq '-?'))) {
help_menu();
} elsif (($#ARGV == 0) && ($ARGV[0] eq '-s')) {
print "Setup\n"
}
}
if ($#ARGV >= 1) {
print "Too many arguments, only one argument may be passed at a time!\n";
}
sub help_menu {
print "Options:\n\n";
print "\t-b\tRun Backup Backup\n";
print "\t-d\tRun Discovery Script\n";
print "\t-h\tShow Help Menu\n";
print "\t-s\tRun Setup Script\n\n";
}
I am wanting to integrate the use of ARGV into my script. After messing with an example of a simple usage I found on Stack Overflow, I was able to make the script "enforce" the use of single command args. The thing that I am wanting to now is to allow for multiple flags instead of just one. The catch is the flags need to be enforced in a specific order if there are multiple used.
Here is the code I have come up with for doing single args and enforcing it.
#!/usr/bin/perl
use strict;
use warnings;
system ("clear");
print "Solignis's Discovery Script v0.6 for ESX\\ESX(i) 4.0+\n\n";
my $numargs = $#ARGV + 1;
if ($#ARGV < 0) {
help_menu();
}
foreach my $argval (0 .. $#ARGV) {
if (($#ARGV == 0) && ($ARGV[0] eq '-b')) {
print "Backup\n";
} elsif (($#ARGV == 0) && ($ARGV[0] eq '-d')) {
print "Discovery\n";
} elsif ((($#ARGV == 0) && ($ARGV[0] eq '-h') || ($#ARGV == 0) && ($ARGV[0] eq '-?'))) {
help_menu();
} elsif (($#ARGV == 0) && ($ARGV[0] eq '-s')) {
print "Setup\n"
}
}
if ($#ARGV >= 1) {
print "Too many arguments, only one argument may be passed at a time!\n";
}
sub help_menu {
print "Options:\n\n";
print "\t-b\tRun Backup Backup\n";
print "\t-d\tRun Discovery Script\n";
print "\t-h\tShow Help Menu\n";
print "\t-s\tRun Setup Script\n\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用核心
Getopt::Long
模块 并且不要担心自己解析参数。如果您有多个参数,则不必按照它们所说的顺序执行任何操作,只需执行类似以下伪代码的操作:
绝对没有理由您的脚本应该允许参数为
-s -b
和不是-b -s
。您的用户会期望,如果他们提供-b -s
,则首先完成设置,然后进行备份。你的脚本应该足够智能。Use the core
Getopt::Long
module and don't worry about parsing arguments yourself.If you have multiple arguments, instead of doing whatever they say in the order they say, you just do something like the following pseudocode:
There's absolutely no reason why your script should allow arguments as
-s -b
and not-b -s
. Your users will expect that if they supply-b -s
that setup will be done first, then backup. Your script should be smart enough.