Search code examples
perlreference

Perl dynamic / symbolic function reference


Given a package name $package and a function name from within that package $function, I can create a reference to that function:

my $ref = eval( "\\&${package}::${function}" );

As a complete example:

#!/usr/bin/perl -w

use strict;

package foo;

sub func()
{
    print "foo::func\n";
}

package main;

my $package = "foo";
my $function = "func";

my $ref = eval( "\\&${package}::$function" );
$ref->();

I do not particularly like that eval() in there and wonder if the same result could be achieved without eval()?


Solution

  • All you need is this:

    my $ref = \&{ "${package}::$name" };
    

    or

    my $ref = \&{ $package . "::" . $name };
    

    Using an expression producing the name of a variable where a variable name is expected is called a symbolic reference. These are usually forbidden by use strict; (specifically use strict qw( refs );), but \& is exempt.