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;
Invocation:
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:  <%-{-{-{-<


In reply to Re: How to find a number and replace it with calculated value? by AnomalousMonk
in thread How to find a number and replace it with calculated value? by Lejocode

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.