me@anywhere.EBay.Sun.COM (Wayne Thompson - IR Workstation Support SE) (04/20/91)
Sure.
#! /usr/local/bin/perl
sub greeting_fn {
print "Hello\n";
1;
}
sub exit_fn {
exit;
}
sub not_found {
print "Not in table\n";
0;
}
%jump_table = (
'Hello', 'greeting_fn'
, 'Bye', 'exit_fn'
);
main: {
while (chop ($name = <STDIN>)) {
eval ("&${jump_table{$name}}") || ¬_found;
}
}
Larry mentioned once (at the BA-LISA perl intro) that you should be able
to say something like:
&$sub_name;
But I guess I don't know the magic incantation. Besides, wrapping it in an
eval let's you test the success of the look up.
Wayne
-- James Brister writes --
Is there an elegant way (other than a massive if-then-else) to do the
following in Perl?
struct { char *name ;
int (*function)() ;
} jump_table [] = {{"Hello", greeting_fn},
{"Bye", exit_fn},
{NULL, NULL}}
i = 0 ;
while (jump_table [i].name && strcmp (jump_table [i].name,command))
i++ ;
if (jump_table [i].function)
(*jump_table[i].function)() ;
i.e. setup a function name/function mapping so I can find the function name
and then call the function.
I've got the Camel Book, if you know of a referrence in there.
Thanks
James