modifying the haystack string inside while($haystack =~ /needle/g) {... }

Y

Yakov

What exactly happens if I modify the $haystack inside such while (see
subject) ?

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.
 
B

Ben Bullock

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.
 
M

Michael Carman

Yakov said:
What exactly happens if I modify the $haystack inside such while
(see subject) ?

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
 
J

jl_post

What exactly happens if I modify the $haystack  inside such while (see
subject) ?

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 )
{
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top