in reply to How to do a "perl -c(w)" check instead of an "eval $string" on a code string

$code .= ";\n1;"; # ... ? my $perl = qx/ which perl /; my $result = qx/ perl -c $code /; # CAN this work? If so, how? I'm a s +hell-tard.

Yes, it can. The my $perl = qx/ which perl / is somewhat pointless, since your are already running perl, so how you've invoked it is in $^X.

my $result = qx/perl -c -e '$code' 2>&1/; # bundle STDOUT and STDERR

should give you either

-e syntax OK

or any error which you can then examine. For simple snippets without quotes, that is! Otherwise you'd grab File::Temp, write a tempfile and examine

my $result = qx/perl -c $tempfile 2>&1/;

update:

WRT evaling - you could switch to some other package before the eval

package My::Eval::Evil; eval $code; if ($@) { .... } package main; # or whatever package you've been in

and then throw away the symbol tables for My::Eval::Evil and the eval'ed code's package. That reduces the risk of name space pollution a bit. But the eval'ed code could still reach into your package (via examining %INC or writing into *main::), so the safest (for some value of safety) is writing a tempfile and shell out a brand new perl.

perl -e 'sub foo {print "foo\n" } package Foo; my $code = "*main::foo += sub {print \"bar\\n\" }"; eval $code; package main; foo()' bar

Replies are listed 'Best First'.
Re^2: How to do a "perl -c(w)" check instead of an "eval $string" on a code string
by Your Mother (Archbishop) on Jan 20, 2009 at 00:57 UTC

    Also nice and good tips. I don't know why I didn't consider tempfiles already. I use them all the time and I've got a uuid already so it can go in the app's files. Sigh.

      If you're interested in success/failure only, you could run system LIST and check the exit code. That would fix the quoting issue of -e:

      system $^X, '-wce', $code and warn "syntax check failed\n";