peter.mao has asked for the wisdom of the Perl Monks concerning the following question:

Dear Santa,
Is there any way to make the replacement text of a substitution increment? For example, say I have the text:
$test = "abc1 abc1 abc1 abc1 abc1";
but I want it to become
abc1 abc2 abc3 abc4 abc5
Is there some expression
$test =~ s/(1)/<..something..>/g;
that would transform the string for me? I've been good all year; please come through for me,
Pete

Replies are listed 'Best First'.
Re: incremental substitution w/ regexp only?
by ikegami (Patriarch) on Dec 25, 2008 at 08:46 UTC
      ikegami! Why that lump of coal? The OPer said he'd been good all year!

      >perl -wMstrict -le "my $test = 'abc1 abc1 abc1 abc1 abc1'; $test =~ s/1/++$1/eg; print $test; " Modification of a read-only value attempted at -e line 1.
      Something like this works better:
      >perl -wMstrict -le "my $addend = 0; my $test = 'abc1 abc1 abc1 abc1 abc1'; $test =~ s/(1)/$addend++ + $1/eg; print $test; " abc1 abc2 abc3 abc4 abc5
        That's not the code I posted. You changed $i (9th letter) to $1 (one). My code works fine.
        >perl -le"$_='abc1 abc2 abc3 abc4 abc5'; s/1/++$i/eg; print" abc1 abc2 abc3 abc4 abc5