in reply to Executing code block in memory

From my perspective, it would be easier to just redirect STDERR to STDOUT (or perhaps to an in-memory scalar), since warnings bypass the normal $@ error capture in eval. There are instructions for redirecting STDERR in open. You could also modify the $SIG{__WARN__} handler (see %SIG in perlvar). Or, as long as you've tossed security to the wind, maybe you could achieve your goal with CGI::Carp  qw(fatalsToBrowser);?


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Executing code block in memory
by morissette (Novice) on Aug 08, 2012 at 21:39 UTC
    I tried this but I dont think its everything you were talking about:
    #!/usr/bin/perl -w use URI::Escape; use HTML::Entities; use CGI qw/:standard/; print "Content-type: text/html\n\n"; my $file; if(param('test')){ my $code = param('test'); $code = uri_unescape($code); $code = encode_entities($code); open STDERR, '>&STDOUT'; open my $fh, '>', \$file; print $fh $code; close $fh; open my $pipe, '-|', "perl -w $file"; close $pipe; close STDERR; }
    The output I get with this is:
    sh: -c: line 0: syntax error near unexpected token `;;' sh: -c: line 0: `perl -w print "hi";'
    This is what is passed to the script:
    print "hi"; print "hello world\n";
      A modified version of your sample that does what I mean:
      #!/usr/bin/perl -w use strict; use URI::Escape; use HTML::Entities; use CGI qw/:standard/; use CGI::Carp 'fatalsToBrowser'; print header; my $file; if(param('test')){ my $code = param('test'); $code = uri_unescape($code); $code = encode_entities($code); open STDERR, '>&STDOUT'; eval $code; print $@ if $@; }

      No need to create external, temporary files. There are some potential messy issues in there, but this is good enough for rough cut.


      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.