In #pm's IRC tonight, Petruchio was looking for a way to use constants (defined via "use constant") in regex's. The no-frills way is to just assign a temporary variable with the constant value, but this leads to extra code. Here's a way to do it with no extra variables. Simply, you need to wrap it in the 'magic' code that forces any expression to be evaluated when it's used in a string (that is '@{[ expr ]}'), and then use the \Q and \E modifiers to tell perl to execute that part of the code before starting the regex.

Update: As MeowChow's pointed out to me, it's not necessary to \Q\E within the substitition part of s/// for this to work, as well as in m// strings as well; code snippet has been updated to reflect this. Mainly, if you do so, realize any special symbols ('.', '{', '}', etc) wil be quoted (eg '.' to '\.'), if you do include the \Q\E.

use constant TEST => 3; my $string = "123456"; $string =~ s/\Q@{[ TEST ]}\E/9/; print $string, "\n"; # 129456 $string =~ s/2/@{[ TEST ]}/; print $string, "\n"; # 139456

In reply to Using constants inside regex by Masem

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.