Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

how to check syntax of code inside a scalar?

by tjking (Novice)
on Aug 04, 2010 at 18:33 UTC ( [id://852941]=perlquestion: print w/replies, xml ) Need Help??

tjking has asked for the wisdom of the Perl Monks concerning the following question:

Hi all, I've got some scripts that dynamically load Perl snippets from the filesystem, setup a few things for them, and then run them through eval(). Is there a way to check the syntax of code contained inside a scalar without having to run 'perl -c' on the external file? TIA
  • Comment on how to check syntax of code inside a scalar?

Replies are listed 'Best First'.
Re: how to check syntax of code inside a scalar?
by tilly (Archbishop) on Aug 04, 2010 at 18:46 UTC
    If you want the check to be right, then no. Nothing but perl can parse Perl.

    However Perl::Tidy does a usually acceptable job of figuring out Perl syntax.

      Uggh, it's a bit shortsighted that there's no built-in function for this. However, after playing a bit, I've found that this can be simulated without having to actually execute the scalar's contents by pre-pending "return;" and testing with eval:

      sub syntax_ok { my $source = "return;\n" . shift; eval $source; return 1 unless $@; return 0; }

      Thanks!

        Bad idea... try it with this:

        syntax_ok(qq{BEGIN { print "yay\n"; }});

        and you'll see that the BEGIN block still gets run, bypassing your return statement. So I'd consider it rather unsafe.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://852941]
Approved by lostjimmy
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-20 04:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found