I realize that "don't do this" is good answer, and , but still, I am
cusious
know what happens if $haystack is modified (nobody does it
conciensly).
I see two-three possibilities
(1) matching position is reset to 0
(2) matching position remains where it was.
(3) next match is forced to fail
... (4) warning is printed ... (5) program dies
Just curious
Y.L.
> What exactly happens if I modify the $haystack inside such while (see
> subject) ?
It would be easier to reply to your message if you didn't put part of
it into the subject like that.
Anyway, "while" just tests for true or false, so of course you can change
$haystack as much as you like inside the loop.
Code from subject [please don't put it there]:
while($haystack =~ /needle/g) { ... }
It's fine to modify the variable in a while loop. In your case, it would
reset the match.
my $s = 'abc';
while ($s =~ /(\w)/g) {
print "$1\n";
$s = 'xyz' if $1 eq 'b';
}
__END__
a
b
x
y
z
There are caveats about modifying an array/list/hash while iterating
over it, but those don't apply here.
-mjc
>What exactly happens if I modify the $haystack inside such while (see
>subject) ?
It's documented in perldoc perlop. The position is reset to 0.
--
Eric Amick
Columbia, MD
You're referring to: while($haystack =~ /needle/g) { ... }
This actually happened to me once. I had to traverse a set of
messages in a string and modify one byte (character) in each message.
However, I discovered that whenever I modified the variable ($haystack
in your case), its pos() would reset to zero and the regular
expression would start matching from the beginning.
To work around that behavior, once I located the byte/character to
change I saved off the pos() value, changed the byte of the message,
and then restored the pos() value of the string, like this:
while ( $haystack =~ m/ ... /g )
{
.
.
.
if ( byte_needs_changing )
{
# Modifying $haystack resets the pos(),
# so save it off and then restore it
# after modifying it:
my $savedPos = pos();
substr($haystack, $offset, 1) = $newByte;
pos() = $savedPos;
}
}
If you use this approach, I recommend leaving the comments in
explaining this, as it's not intuitive for all Perl programmers, and
some will appreciate the explanation.
> I see two-three possibilities
> (1) matching position is reset to 0
Yes, that is it. That's what I discovered on my own, and I
eventually found it documented in the perldocs, but now I can't
remember where.
I hope this helps, Yakov.
-- Jean-Luc