Hello, all--

I've got a question that I can't answer[1]. Given this code:

#!/usr/bin/perl -w use strict; use warnings; while (<DATA>) { if ($. % 10 == 1) { print; for my $cnt (0 .. 3) { <DATA>; # my $t=<DATA>; print; # print $t; } } } __DATA__ Line 0001 Line 0002 Line 0003 Line 0004 Line 0005 Line 0006 Line 0007 Line 0008 Line 0009 Line 0010 Line 0011 Line 0012 Line 0013 Line 0014 Line 0015 Line 0016

I expected to see this:

Line 0001 Line 0002 Line 0003 Line 0004 Line 0005 Line 0011 Line 0012 Line 0013 Line 0014 Line 0015

So imagine my surprise when I saw this:

Line 0001 Line 0001 Line 0001 Line 0001 Line 0001 Line 0011 Line 0011 Line 0011 Line 0011 Line 0011

By changing the two commented lines, I get the desired output, so my program works now. But I can't rest until I know what's causing this behavior. I expect that it has something to do with the nested while and for loops and some interaction with $_.

[1] I've tried to answer it myself, but have been unsuccessful.

Can someone whack me with a cluestick? I'd really appreciate it...

Update: Thanks to everyone who replied. I updated my script and added it to the Code Catacombs.

...roboticus

In reply to Hmmm: while(), file handle and $_ gotcha by roboticus

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.