in reply to syntax check from within perl

The eval function with quoted argument traps compile errors. You can examine the error messages in the perlvar $@. No other special magic is needed. This is not true of eval BLOCK.

Update: <shrug>If you want to avoid runtime on your eval string, just wrap it in a conditional:

$ $ perl -Mstrict -e'$_="printed\n";my$foo=q(print);eval"if(\$^C){$foo}" +;print $@ if $@' -- #no compile or run error $ $ perl -Mstrict -e'$_="printed\n";my$foo=q(quux);eval"if(\$^C){$foo}"; +print $@ if $@' -- # compile error Bareword "quux" not allowed while "strict subs" in use at (eval 1) lin +e 1. $ $ perl -Mstrict -e'$_="printed\n";my$foo=q(&quux);eval"if(\$^C){$foo}" +;print $@ if $@' -- # runtime error $ $ perl -Mstrict -e '$_="printed\n";my$foo=q(print);eval"$foo";print $@ + if $@' -- # conditional removed, no errors printed $
I used $^C, the compile-time flag, for cli convenience, but some $debug would do as well.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: syntax check from within perl
by Anonymous Monk on Mar 02, 2002 at 06:23 UTC
    the only difference is perl will execute whatever code, thus creating any files, emailing /etc/passwd to somebody, or anything else. the dude just ought to run perl -c on the file without reading it.

      Consider:

      #!/usr/bin/perl BEGIN { print "rm -rf /" }

      Guess what happens when you run perl -c on this.

      Now just imagine if that weren't just a print statement...

      Update: I thought it was discussed here before, but I can't seem to find where. IIRC, the verdict was, basically, that there's just not a way to get arbitrary code syntax checked w/o (at least the possbility of) running some of it.

      bbfu
      Seasons don't fear The Reaper.
      Nor do the wind, the sun, and the rain.
      We can be like they are.

        Update: I thought it was discussed here before, but I can't seem to find where. IIRC, the verdict was, basically, that there's just not a way to get arbitrary code syntax checked w/o (at least the possbility of) running some of it.
        It's worse than that. You can't just skip over the BEGIN blocks in your pretend-parser. You must execute them, because they can affect the later parse, and short of solving the halting problem, you basically can't tell whether they'll do something malicious or not, except perhaps by executing them within a Safe compartment. See my "On Parsing Perl" for specific examples of why you cannot skip executing the BEGIN blocks.

        -- Randal L. Schwartz, Perl hacker

        yeah, and how is that less secure than an eval? you can't do anything about code in a BEGIN block short of parsing it out (which can be difficult). you have no point