[thelist] Reg Ex - everything except a phrase
Simon Willison
cs1spw at bath.ac.uk
Wed Sep 10 09:51:11 CDT 2003
Joshua Olson wrote:
> You da man! I'm not familiar with Perl syntax... could you do me a favor
> and explain what this line does:
>
> $d =~ s/^(.*)(?:fred)(.*)$/$1$2/ while $d =~ /fred/; print $d, "\n";
I speak a bit of Perl. The above is easier to understand if you
re-arrange it a bit:
do {
$d =~ s/^(.*)(?:fred)(.*)$/$1$2/
} while ($d =~ /fred/);
print $d, "\n";
The regular expression (now enclosed in the do loop) has already been
discussed: it removes the word 'fred' from the string, but only does so
for the first instance of it. The While part simply keeps repeating the
process until no more instances of 'fred' remain.
I'm not sure how this is any better than using replace though:
$d =~ s/fred//g;
Unless I'm missing something (which is quite likely, I haven't touched
Perl in years).
Hope that helps,
Simon
More information about the thelist
mailing list