[plug] Perl Query...

Christian christian at amnet.net.au
Wed Jan 31 11:36:22 WST 2001


On Wed, Jan 31, 2001 at 11:20:37AM +0800, Trevor Phillips wrote:
 
> Are there any Perl Guru's extraordinaire on this list? I'm trying to figure out
> how to call a subroutine in a Perl module, where the name of the routine is
> arbitary and stored as a string in a scalar.
> eg; If I have a variable bink which has the value bill ($bink = "bill"), such
> that I want to call subroutine bill using bink in module Fred, how would I do
> it??

I'm definitely not a "Perl Guru extraordinaire" but I think I know the
answer to this.  It's covered in the camel book so it's also probably in
the manual pages (perlref at a guess) if you want to do some more
reading on it.

Basically if you have a scalar like $blink which is the name of a Perl
subroutine that you want to call you can do it like this:

&$bink();

Obviously if its part of a module or whatever you'll need to adjust the
syntax for this.  Also note that you can pass parameters into it the
normal way via the parentheses.

The scalar $blink is a symbolic reference and Perl is just treating the
value contained in $blink is the name of the subroutine you want to
call.  I've never actually done this with symbolic references but it
definitely works with hard references and from my 2 minutes of
skim-reading the camel book, I reckon it should work for these too.

> More to the point, how do I do it elegantly? ^_^
> One way I've nutted out is like this:
>   exec "Fred->$bink"
> But that doesn't seem to be very efficient (using exec & all), and gets more
> complex when you want to pass args to $bink...

Does that work?  Weird... I thought exec was just for executing new
programs.

Hope this helps,

Christian.



More information about the plug mailing list