Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Getting brackets right, checking for package subs

by cosmicperl (Chaplain)
on Feb 19, 2009 at 12:40 UTC ( [id://745021]=perlquestion: print w/replies, xml ) Need Help??

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.


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.


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://745021]
Approved by ww
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-05-22 14:15 GMT
Find Nodes?
    Voting Booth?

    No recent polls found