in reply to Using Getopt::Long to call subroutines

Reading commandline options with Getopt::Long is a good thing generally, but seems like overkill for your situation. You could simplify things a bit by using a dispatch table instead.
use strict; use warnings; my %dispatch = ( one => \&sub1, two => \&sub2, three => \&sub3, ); my $arg = shift @ARGV; if (defined $arg && exists $dispatch{$arg}) { $dispatch{$arg}->(); } else { print "Usage: $0 [-command]\n"; print "Available commands:\n"; print " -$_\n" for sort keys %dispatch; } sub sub1 { print "sub one"; } sub sub2{ print "sub two"; } sub sub3 { print "sub three"; }

Replies are listed 'Best First'.
Re^2: Using Getopt::Long to call subroutines
by chinamox (Scribe) on Oct 22, 2006 at 04:10 UTC

    thank you for your swift response!

    I think a dispatch table would be very useful for this simple example but in my actual program I am using @ARGV and the empty <> operator to pass data in from exterior files.

    want my command line too look something like this:

    myusername $: perl myprogram.pl -two /mydire/programs/data

    This way I can run selected subroutines on selected files.

    Thanks for your help!


    -mox
      You can still use that method if you like, as by shifting $arg from @ARGV you remove it from the list of files that will be processed by <>. And you could still use the -two syntax if you liked, here's an example:
      use strict; use warnings; my %dispatch = ( one => \&sub1, two => \&sub2, three => \&sub3, ); sub usage { print "Usage: $0 [-command]\n"; print "Available commands:\n"; print " -$_\n" for sort keys %dispatch; exit 1; } my $arg = shift @ARGV; usage() unless defined $arg; usage() unless $arg =~ /^-/; $arg =~ s/^-//; usage() unless exists $dispatch{$arg}; $dispatch{$arg}->(); sub sub1 { print "one: $_" for <>; } sub sub2{ print "two: $_" for <>; } sub sub3 { print "three: $_" for <>; }