How can I pass command line flags with ARGV while specifying a specific order to the flags?

StackOverflow https://stackoverflow.com/questions/4742305

  •  12-10-2019
  •  | 
  •  

Question

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";
}
Was it helpful?

Solution

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:

if( option s is set ) {
  run setup stuff
}
if( option b is set ) {
  run backup stuff
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top