LPM: Subroutine references, or something ...

Mik Firestone fireston at lexmark.com
Fri Jul 16 07:15:57 CDT 1999


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 ).

HTH,
  Mik
-- 
Mik Firestone fireston at lexmark.com
When I become an Evil Overlord:
I will not grow a goatee. In the old days they made you look diabolic.  Now
they just make you look like a disaffected member of Generation X.

On Thu, 15 Jul 1999, Rich Bowen wrote:

> I do thing weird thing where I figure out which subroutine I'm going to
> call based on arguments/parameters. Then I'll do something like:
> 
> ($foo, $bar) = &{$routine}(@args);
> 
> Works fine.
> 
> The problem is that if I "use strict", I get "Can't use string
> ("whatever") as a subroutine ref while "strict refs" in use at fubar.pl
> line 99."
> 
> My solution thus far has been to "use strict 'vars';" But I would like
> to understand what that error message really means, and how I can do
> what I'm doing another way, so that I can "use strict". Any help or
> pointers (references?) greatly appreciated.
> 
> Rich
> 






More information about the Lexington-pm mailing list