in reply to Re^5: regex in REPLACEMENT in s///
in thread regex in REPLACEMENT in s///
Greetings tybalt89
I wanted to see if I could make yours work with mine, and with a minor tweak, I did. I prefer to use assignment with s///, as in:
(my $tybalt89 = $str) =~ s/...
You did not; to each his own, but to make yours work in my preferred model I removed the /r from the outer regex expression. Once I did that I was able to replace my CODE statement with yours, as a drop-in. I teach math to undergrads with Perl, Python and R, and I have to be able to answer their questions, so I had to understand exactly what is going on here. I also added an extra digit, to see multiple ',' insertions and put the real number into a string. TMTOWTDI, works great, as in:
use 5.20.0; use strict; my $n = 4; my $raw = (1234567.56567); my $orig = (1234567.56567 * $n); say "raw real number: $raw"; say "factored real nbr: $orig"; my $str = "This is a real number ${\($raw * $n)}."; say $str; (my $tybalt89 = $str) =~ s{ \d+ }{ $& =~ s/ \B (?= (?:\d{3})+ $ ) /,/x +rg }xe; say "tybalt89's with assignment and \\r tweak => \'$tybalt89\'"; (my $perlboy = (($raw) =~ s{ \d+\.?\d* }{ $& * 4 }erx )) =~ s{ \d+ }{ $& =~ s/ (?<=\d) (?= (?:\d{3} )+ (?!\d) ) /,/xrg; }ex; say "perlboy's => \'$perlboy\'"; (my $mixed = (($raw) =~ s{ \d+\.?\d* }{ $& * 4 }erx )) =~ s{ \d+ }{ $& =~ s/ \B (?= (?:\d{3})+ $ ) /,/xrg }xe; say "perboy's w/tybalt89's drop-in with \\r tweak => \'$mixed\'"; say "tybalt89's original regex, without assignment => ", ($str) =~ s{ +\d+ }{ $& =~ s/ \B (?= (?:\d{3})+ $ ) /,/xgr }xer; say "tybalt89's original regex, without assignment => ", (1234567.5656 +7 * 4) =~ s{ \d+ }{ $& =~ s/ \B (?= (?:\d{3})+ $ ) /,/xgr }xer; exit(0) __END__
which when run yields:
raw real number: 1234567.56567 factored real nbr: 4938270.26268 This is a real number 4938270.26268. tybalt89's with assignment and \r tweak => 'This is a real number 4,938,270.26268.' perlboy's => '4,938,270.26268' perboy's w/tybalt89's drop-in with \r tweak => '4,938,270.26268' tybalt89's original regex, without assignment => This is a real number 4,938,270.26268. tybalt89's original regex, without assignment => 4,938,270.26268
As I said, the only change to yours was to remove /r from the outer s///. To verify it would insert multiple ',', I added an extra digit and interpolated the real number into a string. So, that \B assertion works, and by removing two look-arounds, probably runs faster than mine.
UPDATE 9/17/2023
Running timethese(-10, {...));
Benchmark: running perlboy, tybalt89 for at least 10 CPU seconds...
perlboy: 10 wallclock secs (10.52 usr + 0.00 sys = 10.52 CPU) @ 25551.33/s (n=268800)
tybalt89: 11 wallclock secs (10.45 usr + 0.00 sys = 10.45 CPU) @ 27807.18/s (n=290585)
Running cmpthese(-10, {...});
Rate perlboy tybalt89
perlboy 25623/s -- -8%
tybalt89 27900/s 9% --
Cheers, and happy perl-ing
|
|---|