bittondb has asked for the wisdom of the Perl Monks concerning the following question:

I want to replace all instances of a regular expression with a value and an incrementing number. So, the replacements would be foo.1, foo.2, etc. How would I do this?

Replies are listed 'Best First'.
Re: Increase number per regex replacement
by runrig (Abbot) on Jan 08, 2002 at 10:00 UTC
Re: Increase number per regex replacement
by theorbtwo (Prior) on Jan 08, 2002 at 10:04 UTC

    The answer lies in the /e option to s///; read perlop.

    Thanks,
    James Mastros,
    Just Another Perl Scribe

Re: Increase number per regex replacement
by belg4mit (Prior) on Jan 08, 2002 at 10:23 UTC
    Just for fun, here's an alternative version without /e ;-)
    $i = 0; @no = qw(one two three four five); foreach ( @no ){ s/e/foo.$i/ && $i++ while /e/; } print "@no\n"; __END__ onfoo.0 two thrfoo.1foo.2 four fivfoo.3

    --
    perl -pe "s/\b;([st])/'\1/mg"

      Ah, but what if you needed to use "fee.$i" as the replacement string instead of "foo.$i"?

      Fee fi foo fum, I smell the infinite loop of an eratum...

      -Blake

        True true, but this was meant to be a whimscial/goldbergian solution. You'd have to be wary of the same issue with /e though not /ge ;-) Of course this fixes that:
        $i = 0; @no = qw(one two three four five); foreach ( @no ){ my $str = ''; while( s/([^e]*)e// ){ $str .= $1 . "fee" . $i++; } $_ = $str . $_; #UPDATED: Append addresses Re: to this node } print "@no\n";

        --
        perl -pe "s/\b;([st])/'\1/mg"