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";
}
Use the core
Getopt::Longmodule 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 -band not-b -s. Your users will expect that if they supply-b -sthat setup will be done first, then backup. Your script should be smart enough.