[Omaha.pm] bad perl - need help - dispatch table

Jay Hannah jay at jays.net
Wed Aug 25 18:26:11 CDT 2004


What's a dispatch table? -grin-

On Aug 25, 2004, at 9:56 AM, Mike Hostetler wrote:
> Take a look at using Getopt or Getopt::Long.  They should be standard
> with your Perl, and they make life easier.  Do a "perldoc Getopt" for
> more info.  A decent page for it is at:
>
> http://www.aplawrence.com/Unix/perlgetopts.html

Yes. Getopt::Long rules.

> 1) Any better way to handle this varied data other than a sub for each
> data type/user input?

If the different do_'s are similar, you should write one (or a few) 
very smart do_* subs, instead of having a seperate sub for each. If 
each operation is wildly different from the last, you'll end up with 
one sub per operation.

If your code gets long (>500 lines?), you should probably split the 
subs into different modules. Just move logical groups of subs out of 
your main program into a .pm file...

MyPackage.pm:    (what would make them similar?)
package MyPackage;

sub do_x1 {  }
sub do_x2 {  }
...

1;

Then in you main program, at the top:

use MyPackage;

That's all there is to know. You're writing packages now. Neat huh? 
When that gets boring, turn your packages into classes and scream OOP! 
at the top of your longs. Objects are good for the soul.

> 2) How can I call the subroutines based on the user input?  Obviously
> &print_$foo as I have below doesn't work.  Maybe a dispatch table
> would work but I can't get that to work the way I want either.

[jhannah-mac:~/tmp2] jhannah% cat j.pl
#!/usr/bin/perl

my $who = $ARGV[0];
&{"do_$who"};

sub do_x {
    print "otay, I'll do_x\n";
}
sub do_y {
    print "otay, I'll do_y\n";
}

[jhannah-mac:~/tmp2] jhannah% ./j.pl x
otay, I'll do_x
[jhannah-mac:~/tmp2] jhannah% ./j.pl y
otay, I'll do_y
[jhannah-mac:~/tmp2] jhannah% ./j.pl z
Undefined subroutine &main::do_z called at ./j.pl line 4.

HTH,

j



More information about the Omaha-pm mailing list