Re: Help, infinite loop on a simple replacement??
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 31 Jan 2006 09:52:15 -0800
pierre_catello@xxxxxxxx wrote:
> Hello,
>
> When trying to replace every % by %25 in a file, my substitution
> command goes into an infinite loop.
>
> while ($input =~ s/%/%25/sg) {}
This says to globally replace every % with %25. If that replacement is
"true" (ie, if there were any % to replace), the while loop conditional
is true, so the block is executed (which does nothing, since it's
empty), and the conditional is checked again. Now it starts at the
beginning of the string and tries to replace every % with %25. If that
replacement is "true" . . . . etc etc etc
> I suspect that inserting a beginning % in the replacement string should
> be the problem (as successive application of the command will match
> it).
You are correct.
> What is the right way to do it?
Why are you using a while loop at all? What made you think that was
something that should be there?
If you want to replace globally, but only once, just do that:
$input =~ s/%/%25/g;
(There was also no reason for the /s modifier in your original)
> In the same idea, if I want to transform any single ' into a double '',
> I will have the same problem using :
>
> while ($input =~ s/'/''/sg) {}
No you won't. Here, you're changing all ' to " the first time through.
After that, the s/// can't find any ' in the string, so the while will
become false. It still makes more sense, however, to just do it once:
$input =~ s/'/"/g;
Paul Lalli
.
- References:
- Help, infinite loop on a simple replacement??
- From: pierre_catello
- Help, infinite loop on a simple replacement??
- Prev by Date: Help, infinite loop on a simple replacement??
- Next by Date: Re: Mechanize and substitution on content, then save
- Previous by thread: Help, infinite loop on a simple replacement??
- Next by thread: Re: Help, infinite loop on a simple replacement??
- Index(es):
Relevant Pages
|