Home > Net >  Export anonymous function from Package
Export anonymous function from Package

Time:10-19

I got a package, lets call it Foo.pm for simplicity. In there, I got some Anonymous functions which I'd like to export.


Foo.pm looks like the following:

package Foo;

use Exporter qw(import);
our @EXPORT_OK = ();
our @EXPORT = qw(
    subroutine1
    subroutine2

    $anon_function
);

subroutine1 {
    # Do something here
}

subroutine2 {
    # Do something else here
}

my $anon_function = sub {
    my $parameter = shift;

    # Do something with parameter

    return 1 if $parameter == 1 or $parameter == 2;
    return 0;
}

In my main script, call it bar.pl, im importing the module and (obviously) using its functions.


bar.pl:

use lib "/usr/share";
use Foo;

subroutine1("foobar");
subroutine2("foobar");

&$anon_function("foobar");

Using the normal subroutines outside of Foo.pm seems no problem, when I get to the &$anon_function() it produces the following error:

Use of uninitialized value in subroutine entry at ./bar.pl line 7 

When trying to print the anonymous function with print Dumper \$anon_function, it also returns $VAR1 = \undef


TL;DR: How can I Export anonymous functions from a Package?

CodePudding user response:

You cannot export a lexical variable. You can only export symbols, i.e. package global variables and named subroutines.

Changing to an our works:

use Exporter qw{ import };
our @EXPORT = qw( $anon );
our $anon = sub { ... };
  • Related