in reply to How to call subroutines using variables ?

I agree with Joost, you should probably use function references as he suggests. However, there's a couple ways to do what you want if you are stuck with a value that is a function name. Cheap way 1:
eval "&$s()";
Or you could try:
&{ &UNIVERSAL::can('main', $s) }();
To rewrite the second example to make it nicer:
my $funcRef = &UNIVERSAL::can('main', $s); if( ref($funcRef) eq 'CODE' ) { &$funcRef(); } else { warn "Function $s not found in package main!"; }
(update: should probably check the return from 'can' to ensure it returns a function reference)

Replies are listed 'Best First'.
Re^2: How to call subroutines using variables ?
by Joost (Canon) on Mar 22, 2007 at 23:10 UTC
    eval "&$s()";
    Oof. Don't do that. It's a lot safer to turn of strict refs instead:
    no strict 'refs'; $s->(); use strict;
    That should still be treated with care, though. It will run ANY subroutine (even in other packages) that can be reached by name. Using your eval STRING option will run ANY code that happens to be in $s. Like:

    $s = "print(); unlink '/etc/passwd'; s";
    updated: fixed quoting
      what if function $s is defined another perl module. Even though i include the perl module .I get this error Undefined subroutine &main::hello
Re^2: How to call subroutines using variables ?
by chromatic (Archbishop) on Mar 23, 2007 at 05:20 UTC

    It's a lot cleaner to use:

    my $func_ref = main->can( $s );

    Checking that $func_ref is true should be sufficient. (Checking ref doesn't always work.)