cosmicperl has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,
  I'm having a hard time getting my brackets right when checking if a subroutine is defined in another package. The problem is the name of the package and the sub are in a scalar called $package and a hash called %rmhash respectively.
I know I could just use eval but that feels like a cop out as I'm sure there is a way to do it just getting the brackets right, I've tried:-
defined &{ {$package}::$rmhash{$runmode} } defined &{ ${$package}::{$rmhash{$runmode}} } defined &{ ${ {$package}::{$rmhash{$runmode}} } } defined &{ ${$package}::$rmhash{$runmode} }
All of which cause errors :(
Thanks for any help.


Lyle

Replies are listed 'Best First'.
Re: Getting brackets right, checking for package subs
by Corion (Patriarch) on Feb 19, 2009 at 12:46 UTC

    It would help us to help you better if you told us, exactly what errors you get in which case.

    Personally, I always use the following snippet to handle symbolic references:

    no strict 'refs'; defined &{ "$package\::$subname" }

    but as I see that you're using a variable named $runmode, I get the feeling that you'd be better served by a simple dispatch table, especially as that brings you some more security:

    my %runmodes = ( init => \&init, login => \&login, ... );
      Ahh brilliant. Thanks. I've adapted this a little and ended up with:-
      defined &{ "${package}::$rmhash{$runmode}" }
      Which works with strict ref turned on.
      I would use a dispatch table, but that runmode hash is from CGI::Application.


      Lyle