in reply to Re: Dynamically Creating a Code reference
in thread Dynamically Creating a Code reference

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.

Replies are listed 'Best First'.
Re^3: Dynamically Creating a Code reference
by bart (Canon) on Jun 16, 2006 at 13:07 UTC
    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.