[San-Diego-pm] Recompiling global substitution RE?

Gautam Dey gautam.dey77 at gmail.com
Sat Mar 20 08:41:38 PDT 2010


Reuben,

   Trying to figure out how you are determining when to do the substitution?



2010/3/19 Reuben Settergren <ruberad at gmail.com>:
<snip>
>
> #! /bin/perl
> $s = "1 2 3 1 2 3 1 2 3";          # what I have
> $t = "sg1s 2 3 sr1s 2 3 1 sy2s 3"; # what I want

How do you know that there are two elements after the first 1 to generate
the "sg1s 2 3" and that there are three elements after the 1 to generate the
"sr1s 2 3 1" and that there is only 1 element after the 2 to generate the
"sy2s 3". The transformation seem a bit more complicated then what can
be done with a simple regular expresion .

s/something/text/g replaces all occurrences of something with text.
So, you regular expression seems to be replacing all occurrences of 1
with the appropriate  evaluated code.  But, I'm not sure as
's!($nums[$i++])!s$cols[$j++]$1s!g'  is a bit on the unusual side of things.

Gautam.

> @nums = qw(1 1 2);
> @cols = qw(g r y);
> $i=$j=0;
> $s =~ s!($nums[$i++])!s$cols[$j++]$1s!g;
> print "Want: '$t'\n";
> print "Got:  '$s'\n";
> print "i is now $i\n";
> print "j is now $j\n";
>
> The output of this program is unfortunately:
>
> Want: 'sg1s 2 3 sr1s 2 3 1 sy2s 3'
> Got:  'sg1s 2 3 sr1s 2 3 sy1s 2 3'
> i is now 1
> j is now 3
>
> Perl ended up incorrectly coloring the third ‘1′ yellow, instead of the
> third ‘2′, because in the substitution regular expression, the left
> (matching) side was evaluated/compiled only once, while the right
> (replacement) side was evaluated/interpolated three times (as desired).
>
> I know that there are ways to force the left side of the RE to compile only
> once (/o modifier, qr// operator), and there are ways to force eval in the
> right side (/e and /ee modifiers — although in this case, standard
> interpolation was sufficient), but is there any way I can force
> the left side to compile multiple times? (Even within the same /g
> substitution?) I tried a few constructs using the \G (start matching from
> previous position) zero-width assertion, but only managed to get myself into
> infinite loops.
>
> I'd appreciate any help anyone can offer -- including "What an idiot, the
> RIGHT way to do that is completely different! (And here it is...)"
>
> thx for thinking for me!
>
> r
>
>
>
> _______________________________________________
> San-Diego-pm mailing list
> San-Diego-pm at pm.org
> http://mail.pm.org/mailman/listinfo/san-diego-pm
>


More information about the San-Diego-pm mailing list