[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

FW: [FWP] Substitution



> From: Juanma Barranquero [mailto:barranquero@laley-actualidad.es] 
> Sent: Sunday, June 20, 1999 11:55
> To: fwp@technofile.org
> Subject: [FWP] Substitution
...
> Substituting a substring ($pat) inside of a big (>500K) string
> ($text), but the first time it is changed to one thing ($s1) and
> afterwards it is changed to another thing ($s2). Also, $s1 contains
> the original $pat (in fact, it is $pat . $s2). So far, the best we've
> been able to come with is:
> 
> $text =~ s/$pat/$s1/;
> 1 while ($text =~ s/$pat(.*?)$pat/$pat$1$s2/);
> 
> but obviously it is horribly inefficient.
> 
> Does someone know of a better/faster way? Is there any one-liner for
> that?

Yes.

> P.S.: I hope this is not against the spirit of Fun With Perl. I know
> how implement it with index, etc., but it is very puzzling not being
> able to find a regexp way to do that...

Don't be disheartened!


#!/usr/local/bin/perl -w
#use strict;

my $test = 'foobarbazfoobarbaz';
my ($pat, $s1, $s2) = qw(bar aaa zzz);

$test =~ s/$pat(.*?)$pat/$s1$1$s2/;

print "$test\n";

==== Want to unsubscribe from this list? (Don't you love us anymore?)
==== Well, if you insist... Send mail with body "unsubscribe" to
==== fwp-request@technofile.org