Gossamer Forum
Home : General : Perl Programming :

is this possible?

Quote Reply
is this possible?
I'm pretty sure its not possible, but maybe someone can prove me wrong.

If I have a simple perl file that does whatever function, and I parse the file into a string, is it possible to run the actual code from the string?


my $string = "lines of perl code";

# some function to execute the code...

execute_code($string);


??? Something like that maybe?

- Jonathan
Quote Reply
Re: [jdgamble] is this possible? In reply to
Code:
my $data = "sub { return 'Testing 123'; }";
my $code = eval($data);
print $code->();

In the example above $data holds a simple string of perl code. By calling eval() with $data as an argument the code is compiled and the result is a CODE reference due to the anonymous subroutine I've wrapped the code with. You can then execute the code using $code->();

The simpler version is...

Code:
my $data = "return 'Testing 123';";
print eval $data;

Edit: I forgot to mention that you should check whether $@ has been set which will indicate if your perl code has syntax errors (the code in the string being compiled).

Last edited by:

Gmail: Feb 4, 2005, 8:49 AM
Quote Reply
Re: [Gmail] is this possible? In reply to
Thanks, that was what I was looking for.

- Jonathan