I was knocking my head against a bug in my code when I came across Perlish behavior I don't really understand. I reduced the code to the bare minimum to best show the behavior.
#!perl use strict; use warnings; my $data = 'some random data to test this'; while (my ($line) = $data =~ m/^(.*)$/gm) { print "<0>" . $line ."\n"; }
The above code will output indefinitely:
<0>some . . <0>some <0>some
Now, if we modify the code just a little bit, we get the following code and behavior, which is what I wanted:
#!perl use strict; use warnings; my $data = 'some random data to test this'; while ($data =~ m/^(.*)$/gm) { my $line = $1; print "<1>" . $line ."\n"; }
The above will output what I expect:
<1>some <1>random <1>data <1>to <1>test <1>this
To get it out of the way, someone might say why don't I do the below instead? The behavior is the same as above. To avoid dirty details, yes, that's true. I just want to preserve $_ deeper within the while{} block
while ($data =~ m/^(.*)$/gm) { print "<2>" . $1."\n"; }
Can someone explain why the first code sample doesn't work as I would expect? The only thing I can think of is that the RegEx pointer isn't being preserved on each iteration, but I don't understand why....
In reply to While behavior by SavannahLion
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |