perlboy_emeritus has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: regex in REPLACEMENT in s///
by tybalt89 (Monsignor) on Sep 12, 2023 at 19:51 UTC | |
by ikegami (Patriarch) on Sep 12, 2023 at 22:53 UTC | |
by tybalt89 (Monsignor) on Sep 12, 2023 at 23:21 UTC | |
by ikegami (Patriarch) on Sep 14, 2023 at 12:41 UTC | |
by tybalt89 (Monsignor) on Sep 14, 2023 at 12:52 UTC | |
by perlboy_emeritus (Scribe) on Sep 12, 2023 at 20:13 UTC | |
|
Re: regex in REPLACEMENT in s///
by hippo (Archbishop) on Sep 12, 2023 at 19:57 UTC | |
by choroba (Cardinal) on Sep 12, 2023 at 20:05 UTC | |
by hippo (Archbishop) on Sep 13, 2023 at 09:52 UTC | |
by perlboy_emeritus (Scribe) on Sep 14, 2023 at 16:16 UTC | |
by tybalt89 (Monsignor) on Sep 14, 2023 at 21:27 UTC | |
| |
by Bod (Parson) on Sep 12, 2023 at 21:57 UTC | |
by haukex (Archbishop) on Sep 13, 2023 at 06:37 UTC | |
by Bod (Parson) on Sep 13, 2023 at 10:42 UTC | |
by perlboy_emeritus (Scribe) on Sep 12, 2023 at 20:19 UTC | |
|
Re: regex in REPLACEMENT in s///
by Anonymous Monk on Sep 13, 2023 at 10:52 UTC |