in reply to Numbering instances of a String in a file

use strict; use warnings; my $cnt = 1; while (<>) { s/$/sprintf '%04d', $cnt++/e if /^\*+$/; print; }

Update: The above code functionally satisfies the OP specification. Thanks to ikegami for demonstrating several optimization techniques below.

Replies are listed 'Best First'.
Re^2: Numbering instances of a String in a file
by ikegami (Patriarch) on Jun 07, 2010 at 17:33 UTC

    Needless sprintf, needless match, and you should probably separate the number from the stars with a space. I'd also require at least 3 stars to trigger a match.

    my $cnt = '0000'; while (<>) { s/^(\*{3,})$/"$1 ". ++$cnt/e; print; }

    Optimised: (requires 5.10+)

    my $cnt = '0000'; while (<>) { s/^\*{3,}\K$/" ". ++$cnt/e; print; }

    As a one-liner: (Second version requires 5.10+)

    perl -pe'BEGIN { $cnt = '0000' } s/^(\*{3,})$/"$1 ". ++$cnt/e' perl -pe'BEGIN { $cnt = '0000' } s/^\*{3,}\K$/" ". ++$cnt/e'
      Without an eval:
      perl -ple 'BEGIN {$cnt = '0000'} $_ .= " " . ++$cnt if /\*{3,}$/'
        None of the solutions used an eval. That would be /ee.