gctaylor1 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

My current script looks something like this:

if ($ARGV[0] eq "-H"){ print "Help goes here\n"; } elsif ( $ARGV[0] eq "-L") { print "List of things here\n"; } elsif ( $ARGV[0] eq "-Action") { my $parameter1 = $ARGV[1]; my $parameter2 = $ARGV[2]; print "Rest of program here\n";}
but I want to add things like example 4, and maybe 5 :

Example 1 bash$ ./scriptname.pl action_1 # this already works
or
Example 2 bash$ ./scriptname.pl action_2 # this already works
or
Example 3 bash$ ./scriptname.pl action_3 parameter1 parameter2 # this already works
or
Example 4 bash$ ./scriptname.pl action_4 parameter1 parameter2
or
Example 5 bash$ ./scriptname.pl action_N parameter1 parameter2
.
.
.
The script started out with a single purpose and it flows well enough. I set it up with as many subroutines as possible and I just run down the script calling subroutines where I can until I get to the end. Now that I want to add more functionality where additional actions will be determined on the command line I'm not sure how to do it. I only want to do one action at a time but am not sure how to organize the script.

I have 3 ideas:

Thank-you for any insight.

  • Comment on What's the best way to make my script execute different sections without using goto?
  • Download Code

Replies are listed 'Best First'.
Re: What's the best way to make my script execute different sections without using goto?
by ikegami (Patriarch) on Feb 24, 2009 at 17:32 UTC

    Getopt::Long will help you here.

    In a more general situation, you'd want a dispatch table.

    my %actions = ( action1 => \&action1, action2 => \&action2, action3 => \&action3, ); my $action_sub = $actions{$action} or die("Unknown action $action\n"); $action_sub->(@ARGV);
Re: What's the best way to make my script execute different sections without using goto?
by revdiablo (Prior) on Feb 24, 2009 at 21:03 UTC

    I would use a dispatch table with a bunch of subroutines, one for each action. The dispatch table makes it easy to use the command line argument to call the proper bit of code. Simple example:

    my %ACTION_NAMED = define_actions(); my $action = shift; # First argument my @args = @ARGV; # Remaining arguments if (exists $ACTION_NAMED{$action}) { $ACTION_NAMED{$action}->(@args); } else { $ACTION_NAMED{_default_}->(@args); } sub define_actions { return ( action1 => \&action1, action2 => \&action2, _default_ => \&usage, ); } sub action1 { ... } sub action2 { ... } sub usage { ... }
      I'm going to go read about dispatch tables

      Thank-you for your time and advice.