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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.