I am given a code string by user, and wants to know if the code contains statements or special blocks that are executed not in regular run time.
Impossible with a static parse (Update: the classic links on "only perl can parse Perl": On Parsing Perl and Perl Cannot Be Parsed: A Formal Proof, and tye's reply to the latter). Consider for example eval(uc('end').'{...}') or something more convoluted, like variations on s s s END { ... } see (Update 3: like s x x qq s \Uens.'D{...}' xexe).
The only way to do this safely is to limit the user to a subset of Perl that is statically parseable. See the new module standard and Sawyer's recent talk on it.
Update 2: As LanX points out, B::Deparse is not perfect, and using standard unfortunately doesn't protect you from those issues either. It would be possible to keep both the original standard-conforming string (checked to ensure it doesn't contain any BEGIN, eval, do, use, and so on) and its evaled coderef, e.g. in an object that could overload stringification and coderef-dereferencing, but that might be overkill depending on what you're trying to do.
In reply to Re: Knowing when a code string contains code that will be executed at compile-time/end? (updated)
by haukex
in thread Knowing when a code string contains code that will be executed at compile-time/end?
by perlancar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |