Search code examples
perlsubroutine

Perl sub made from string


I am trying to use a sub in perl that is contained in a string.

Currently I have something like

$sub = "sub{ my $in = shift; if($in =~ /bla.*wam/){return 1;}}";

I try and use it by doing

$sub->("test");

or

&{$sub}->("test");

both examples above just spit out the whole function as if it were the name of a sub it could not find. It looks like this:

Undefined subroutine [function then printed here]

What am I getting wrong here?


Solution

  • Let's say that the scalar $sub contained the string "foobar". If you then say $sub->(), then you are attempting to call a subroutine named foobar. If that subroutine does not exist, you will get an error.

    You are trying to call a subroutine with the name sub{ my $in = shift; if($in =~ /bla.*wam/){return 1;}}, which is a thoroughly ridiculous name for a sub and obviously doesn't exist in your program. (And actually, since it's double-quoted, $in is probably interpolated as something without you realizing it.)

    So, first of all, don't do that.

    If you want an anonymous subroutine, make it like this:

    my $sub = sub { my $in = shift; if($in =~ /bla.*wam/) { return 1; } };
    

    Then execute it like this: $sub->("test");

    If you really need to execute code in a string, then you can use eval.

    my $sub = eval 'sub{ my $in = shift; if($in =~ /bla.*wam/) { return 1; } }';
    

    That will evaluate the code in the string and return the result, which is a sub reference. Be very careful where these strings are coming from. Whoever makes them can make your program do whatever they want.