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

Hugh Jarce hjarce2001 at yahoo.com
Thu Aug 26 04:29:55 CDT 2004


Jay Hannah wrote:
> [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.

Nice idea.
Here's a version of that idea that works with use strict
(and with a bit more error handling):

#!/usr/bin/perl
use strict;

sub Handler::x {
    print "otay, I'll do_x\n";
}
sub Handler::y {
    print "otay, I'll do_y\n";
}

my $who = $ARGV[0];
&{$Handler::{$who} || sub { die "don't know how to do $who\n" }};

However, I might write it with a manual dispatch table like this,
because it's faster. ;-)

#!/usr/bin/perl
use strict;

sub do_x {
    print "otay, I'll do_x\n";
}
sub do_y {
    print "otay, I'll do_y\n";
}
my %dispatch_table = (
    x  => \&do_x,
    y  => \&do_y,
);

my $who = $ARGV[0];
exists($dispatch_table{$who})
   or die "don't know how to do $who\n";
$dispatch_table{$who}->();

Hugh.



		
__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - Send 10MB messages!
http://promotions.yahoo.com/new_mail 


More information about the Omaha-pm mailing list