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

Hello monks
I have a simple problem
Basically i am reading a file and i am searching each line
of the file for a pattern like &#[\d]{5}.
but the problem is i dont know hom many of this pattern will
be there in the line. I would like to replace each of
these with a different pattern.
Any help appreciated
Thanks

update (broquaint): title change (was regex)

Replies are listed 'Best First'.
Re: repeated replacement regex
by Abigail-II (Bishop) on Feb 11, 2003 at 09:57 UTC
    # Untested code my @replacements = ( ... ); while (<>) { my $i = 0; 1 while s/\d{5}/$replacement[$i++]/; }

    Abigail

      Nice solution with one little caveat, none of the replacements should match '\d{5}' ...

      -- Hofmator

        Thanks a lot
        Thats working just right for me
Re: repeated replacement regex
by BrowserUk (Patriarch) on Feb 11, 2003 at 11:59 UTC

    This seems to handle the pathological cases?

    #! perl -lsw use strict; my @reps = map{ sprintf '%05d', $_ } 0 .. 20; while(<DATA>) { my $n=0; # redundant /e option removed # per [Abigail-II]'s comment below. s/\d{5}/$reps[$n++]/g; print; } __DATA__ 0000000000000000000000000000000000000000000000000000000000000000000000 +0000000000000000 00000xxxx00000xxxxx00000xxxx00000xxxxx00000xxx00000xxx00000xx00000xxx0 +0000x00000x00000

    Outputs

    c:\test>234342 0000000001000020000300004000050000600007000080000900010000110001200013 +0001400015000160 00000xxxx00001xxxxx00002xxxx00003xxxxx00004xxx00005xxx00006xx00007xxx0 +0008x00009x00010

    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

      Why the /e?

      Abigail

        No good reason!

        'cept I often add it to allow me to print $& etc. when debugging, and I forgot to remove it.


        Examine what is said, not who speaks.

        The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.