Search code examples
perlgetopt

Getopt::Long multiple switches


I have three methods and two switches

I would like

  • MethodA to be run if SwitchA is set
  • MethodB to be run if SwitchA and SwitchB is set
  • MethodC to be run if SwitchA and SwitchB is set and an arguement for SwitchB is produced

Like so

./main --switchA
./main --switchA --switchB
./main --switchA --switchB Hello

My code

my $result = GetOptions{
             "SwitchA" => \$opt_a,
             "SwitchB:s" => \$opt_b
   };
            

 methodA if($opt_a);
 methodB if($opt_a && $opt_b eq "");
 methodC if($opt_a && $opt_b ne "")

I have tried different things but essentially, If I just want MethodB to run, Method A always runs, and if I want MethodB to run, MethodA always runs.

Haven't got round to testing MethodC yet.


Solution

  • methodA if $opt_a && !defined($opt_b);
    methodB if $opt_a && defined($opt_b) && $opt_b eq "";
    methodC if $opt_a && defined($opt_b) && $opt_b ne "";
    

    or

    if ($opt_a) {
       if (defined($opt_b)) {
          if ($opt_b eq "") {
             methodB
          } else {
             methodC
          }
       } else {
          methodA
       }
    }