Gossamer Forum
Home : General : Perl Programming :

Calling subroutine by variable

Quote Reply
Calling subroutine by variable
I'm trying to figure out a straightforward way to call a subroutine using a variable containing the name. The below doesn't work when use strict is on but should help you see what I'm after.
Code:
sub abc123 {print "I'm output from sub abc123"}

$var = abc123;
&$var;

Any suggestions?
Quote Reply
Re: [Eric P] Calling subroutine by variable In reply to
hmmm, can't seem to edit my own post.

That should be $var = "abc123" with quotes.
Quote Reply
Re: [Eric P] Calling subroutine by variable In reply to
this works fine under strict:

Code:
use strict;

my $foo = sub { return "output" };

print &$foo;

Philip
------------------
Limecat is not pleased.
Quote Reply
Re: [Eric P] Calling subroutine by variable In reply to
After you "use strict", you can also un-strict things. In this case, you need:

Code:
no strict "refs";

In the example below, I have it enclosed in a block to limit the scope.

Code:
use strict;

sub foo {
return "output";
}

my $var = "foo";

{
no strict "refs";

print &$var;
}

Philip
------------------
Limecat is not pleased.