in reply to Dynamically Creating a Code reference

What you wanted to do all along is this:
$coderef = eval "sub { $code }";
plain and simple. I'm surprised none of the other, many replies suggested as much.

Check the return value of the eval and/or $@, if the eval fails and returns undef, you must have had a syntax error.

Replies are listed 'Best First'.
Re^2: Dynamically Creating a Code reference
by Herkum (Parson) on Jun 16, 2006 at 12:38 UTC

    NOTE, I did not correctly read the parent post! The parent was absolutely correct.

    Sorry, this does not work, you are doing what I did originally, which was

    sub { $code };

    Which treats $code as a string instead of perl code. This of it this way,

    eval sub { 'print "I love perl\n;" }

    this will not return an error and still does nothing except return the the string I just had in there. The eval has to be in the sub for the string.

      I think you did something wrong, perhaps you used single quotes instead of double quotes. As it is in my code, the string is inserted in the sub definition before it is evalled. Try this:
      $code = 'print "I love perl\n";'; $coderef = eval "sub { $code }"; $coderef->(); print "Don't believe me?\n"; $coderef->();
      Result:
      I love perl Don't believe me? I love perl

        I misread the code sample you gave me and the code that I posted, I did test, and it did exactly what I said. Which was totally different from what you stated.

        You are right, I am wrong this does work.