LPM: Subroutine references, or something ...

Rich Bowen rbowen at rcbowen.com
Fri Jul 16 07:47:42 CDT 1999


Mik Firestone wrote:
> 
> Rich, others have explained the problem but ( as I was driving home ) it
> occurred to me you may not have the solution :)  To my memory, I got this
> either from the cookbook or CGI.pm.  Basically, to get around this problem
> make a hash of function references.  To use your example, it would look
> something like:
>     %functions = ( this => \&dothis,
>                    that => \&dothat,
>                    exit => \&exit,
>                  );
>     . . . # Lots of wonderful code happens here
>     if ( defined ( $functions( $routine ) ) ) {
>         ($foo,$bar) = $functions{$routine}->(@args);
>     }
>     else {
>         die "I am sorry, I cannot do $routine!\n";
>     }
> 
> This will run under use strict and gives you pretty much the same
> functionality.  On the downside, you have to remember to add each new function
> that you need to the hash ( which is why I usually include the if-else
> structure ).

Thanks. That helps immensely. I was trying to figure out how to
incorporate Graydon and Steve's comments into my code, and was not
getting very far. It did not occur to me to put subroutine references
into the function hash. Very sneaky. I usually have to maintain an array
of valid subroutines anyway, so that I don't call an undefined function
by mistake, so that's not any additional hardship.

Thanks all for your input. This makes life easier.

Rich
-- 
It seems to me as we make our own few circles 'round the sun
We get it backwards and our seven years go by like one 
          --Rush, 'Dog Years' (Test for Echo, 1996)



More information about the Lexington-pm mailing list