in reply to Executing code block in memory

This sounds like a job for Capture::Tiny.


Dave

Replies are listed 'Best First'.
Re^2: Executing code block in memory
by morissette (Novice) on Aug 08, 2012 at 20:36 UTC

    Here's the output:

    Stdout: Stderr: Result: print "hi";

    Here's my test code

    #!/usr/bin/perl use URI::Escape; use HTML::Entities; use Capture::Tiny qw/capture/; use CGI qw/:standard/; print "Content-type: text/html\n\n"; if(param('test')){ my $code = param('test'); $code = uri_unescape($code); $code = encode_entities($code); my($stdout, $stderr, @result) = capture { $code }; print "Stdout: $stdout\n"; print "Stderr: $stderr\n"; print "Result: @result\n"; }

    Obviously what I really want to be returned here is the word: 'hi'. Maybe that clears up what I am trying to do.

      Capture::Tiny doesn't actually evaluate a string as code. You still need to use eval (or Safe) for that. Here's a minimal example:
      use strict; use warnings; use Capture::Tiny qw/capture/; my $code = 'print "hi"'; my($stdout, $stderr, @result) = capture { eval $code }; print "Stdout: $stdout\n"; print "Stderr: $stderr\n"; print "Result: @result\n";

      The output will be:

      Stdout: hi Stderr: Result: 1

      You might be wondering where "1" comes from. print returns true on success, and that propagates through the eval back to capture, which rolls it into the result set.

      Now once you introduce Safe (which I suspect you probably will end up doing), things get a lot more complicated really fast, and you'll still be exposed to DOS attacks.


      Dave