in reply to How to find a number and replace it with calculated value?
The multi-pass approach used by toolic here is effective and sane. But if you really want to over-engineer the heck out of this problem, you could move all the parsing and string generation off to a module, which could be quite simple, not even exporting anything:
Module Lame.pm:
package Lame; use 5.010; use warnings; use strict; my $rx_Z = qr{ (?<! [[:alpha:]]) Z \s* = \s* (?{ 'Z' }) }xms; my $rx_XP = qr{ (?<! X) XP (?! P) (?{ 'XP' }) }xms; my $n_XP = 0; my %dispatch = ( 'Z' => sub { my ($n) = @_; return $n * 5; }, 'XP' => sub { ++$n_XP; return qq{ ($n_XP)}; }, ); sub parse { my ($sr_s) = @_; $$sr_s =~ s{ (?| $rx_Z \K (\d+) | $rx_XP \K) } { $dispatch{$^R}->($1, $2, $3, $4, $5, $6, $7) }xmseg; } 1;
c:\@Work\Perl\monks\Lejocode>perl -wMstrict -le "use Lame; ;; my $s = 'a Z=4 b ZZ=1 c Z = 123Z=99d XP e XXPP f XP gXPh'; print qq{'$s'}; ;; Lame::parse(\$s); print qq{'$s'}; " 'a Z=4 b ZZ=1 c Z = 123Z=99d XP e XXPP f XP gXPh' 'a Z=20 b ZZ=1 c Z = 615Z=495d XP (1) e XXPP f XP (2) gXP (3)h'
Update: Lame.pm should probably also include a setter for $n_XP:
sub set_XP { $n_XP = $_[0]; }
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to find a number and replace it with calculated value?
by Lejocode (Novice) on Mar 04, 2017 at 10:56 UTC |