"Tom Allison" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> #!/usr/bin/perl
> use strict;
> use warnings;
> sub f {
> my $value = shift;
> print $value,"\n";
> }
> sub g {
> my $value = shift;
> print "\t",$value,"\n";
> }
> my $var = shift;
> my $code = \&$var;
> &$code("test");
> =============================
> I got this working well enough but it's not quite what I'm looking for.
> I hope I'm close.
>
> I need to make sure that the value in $var is a function that exists...
> Is there some method to do that which isn't going to require a LOT of
> overhead. I was thinking this might be a fast solution (unproven).
along with the other responses, this also works:
$ cat dispatch.pl
use strict;
use warnings;
sub f {
my $value = shift;
print $value,"\n";
}
sub g {
my $value = shift;
print "\t",$value,"\n";
}
my $var = shift or die("usage: $0 f|g\n\n");
# main is the package the function was defined
# can is a method defined in UNIVERSAL, the base class
# for all packages. All packages inherit from UNIVERSAL.
# you could also write this line as:
# if ( my $code = UNIVERSAL::can( main => $var ) ) {
if ( my $code = main->can( $var ) ) {
$code->( 'arg1' );
} else {
die("\ninvalid dispatch code: [$var]\nusage: $0 f|g\n\n");
}
$ perl dispatch.pl
usage: dispatch.pl f|g
$ perl dispatch.pl f
arg1
$ perl dispatch.pl g
arg1
$ perl dispatch.pl b
invalid dispatch code: [b]
usage: dispatch.pl f|g
$ perl dispatch.pl z
invalid dispatch code: [z]
usage: dispatch.pl f|g
Todd W.
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>