You can interpolate regexes into substitutions just fine without having to fear code execution.

$string =~ s/$regex/$replacement/g;

will interpret $regex as a regex, which can be user input, and $replacement as a string. Note that this way $1, $2 is not available in the replacement.

There is a risk though: it is possible to craft a regex that takes ridiculous amounts of time to match against a string of moderate length. So if you plan to run this on a web server where people can enter aribrary regexes, don't do that.

However, my code editor (Smultron) does global subs using perl regex without any limitations of the expression input that I have yet discovered, so it would seem that there must be a safe way to do this.

The author of your code editor probably assumed correctly that if you are already running an editor on your machine, you wouldn't need to use a regex to slow down the computer - you could just launch another program which does that job for you.

Or formulated differently, if you try to hurt somebody by putting an "evil" regex into the search box, you'll only hurt yourself.

Note that Safe is a core module that is designed to safely execute foreign perl code, but is considered insecure by its authors, and doesn't offer any protection against slow regexes either.


In reply to Re: safe method to execute perl code with user input? by moritz
in thread safe method to execute perl code with user input? by Allasso

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.