Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: how to check syntax of code inside a scalar?

by tilly (Archbishop)
on Aug 04, 2010 at 18:46 UTC ( #852944=note: print w/replies, xml ) Need Help??


in reply to how to check syntax of code inside a scalar?

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.

  • Comment on Re: how to check syntax of code inside a scalar?

Replies are listed 'Best First'.
Re^2: how to check syntax of code inside a scalar?
by tjking (Novice) on Aug 04, 2010 at 19:42 UTC

    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.

        This does however seem to match the perl -c syntax check. From perlrun:
               -c   causes Perl to check the syntax of the program and then exit
                    without executing it.  Actually, it will execute "BEGIN",
                    "UNITCHECK", "CHECK", and "use" blocks, because these are
                    considered as occurring outside the execution of your program.
                    "INIT" and "END" blocks, however, will be skipped.
        
        perl -c -e 'BEGIN { print "yay\n"; }; print "boo\n"'
        yay -e syntax OK

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (8)
As of 2022-08-19 13:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?