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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.