in reply to run-time syntax checking

If this is run in a safe environment an easy way to eval the code without it actually running could be to put into a closure (this technique is done by HTML::Mason, which can load a component separately from executing it):
eval "sub { $code }"; die "Compilation failure: $@" if $@;
Of course this simple piece of code could be improved, since a comment at the end of $code could break things.
my $closure = eval "sub {\n$code\n}";
You call then invoke &$closure (or $closure->()) when you want to actually execute the code.

--
integral, resident of freenode's #perl

Replies are listed 'Best First'.
Re: Re: run-time syntax checking
by abell (Chaplain) on Jan 31, 2003 at 13:55 UTC

    Some more thought is required, as one could pass

    } do nasty stuff; ... my $foo = <<"}";
    as $code.

    This way, one could close the sub, execute whatever and keep the syntax correct by using the outer } as heredoc terminator.

    Antonio

    The stupider the astronaut, the easier it is to win the trip to Vega - A. Tucket

      There is no protection against malicious code without Safe and even then it can have unwanted side-effects: never returning and other DoS conditions.


      Seeking Green geeks in Minnesota

Re^2: run-time syntax checking
by Aristotle (Chancellor) on Jan 31, 2003 at 13:12 UTC
    You're in for a surprise if $code contains a closing curly too much, though.

    Makeshifts last the longest.

      root@Captain:/home/pardus# perl my $string = "print 'some string'; }"; my $sub = eval "sub { $string }"; print $@; Unmatched right curly bracket at (eval 1) line 1, at end of line syntax error at (eval 1) line 1, near "} }"
      So where is the surprise ?
      --
      Jaap Karssenberg || Pardus (Larus)? <pardus@cpan.org>
      >>>> Zoidberg: So many memories, so many strange fluids gushing out of patients' bodies.... <<<<
        How about
        my $string = '}{ print "Bwahaha!\n"; system("rm -rf /")';

        Makeshifts last the longest.