Hello Monks;

I've been asked to review and refactor/optimize a large collection of perl5 scripts, and a great many that include regular expressions would appear to benefit from s///e, the eval modifier, as in s/PATTERN/CODE/e, iff I can substitute ANY regex for CODE. Programming Perl 4th, pg 254 says, to wit: "Applications of this technique are limitless", and I agree if I can generalize the use of any regular expression in CODE. However, things are not going according to plan in my perl (v5.36.1) built for darwin-2level. A very simple case in point (I have much more complex instances once I can get this basic example to work.

my $str = 'This ia a real number, 123456.56'; say $str; (my $res = $str) =~ s{ (\d+) }{ sprintf("%s", 4*$1) }xe; # $1*4, just +to show /e works say $res; say "\$1 = $1"; (my $adj = $1) =~ s/(\d)/3/g; # replace each \d with '3', same reason say $adj; ($res = $str) =~ s{ (\d+) }{ ($adj = $1) =~ s/(\d)/3/g }xe; # replace +'123456' with '333333', proof of concept say $res;

This yields:

   This ia a real number, 123456.56
   This ia a real number, 493824.56
   $1 = 123456
   333333
   This ia a real number, 6.56

The resulting string after substitution should be 333333.56. There are, indeed 6 substitutions, so it looks like the boolean value of each iteration is being substituted. The fragment '($adj = $1) =~' I believe is required because $1 is immutable, and the result is the same with /ee. Any suggestions re patterns of regex expressions in the CODE part of S/PATTERN/CODE/ would be very appreciated.

Thanks Monks for your help.


In reply to regex in REPLACEMENT in s/// by perlboy_emeritus

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.