[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Omaha.pm] bad perl - need help - dispatch table
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