Why is the $_ variable of the outer foreach() loop getting clobbered by the inner while() loop in the code, below?
1 #! /usr/bin/perl -w 2 3 my @test_files = glob "*.txt"; 4 5 foreach (@test_files) { 6 print "Starting processing of file, $_.\n"; 7 open TEST_FILE, "< $_" or die "Couldn't open test file, '${_ +}', for reading: ($!)"; 8 9 while (<TEST_FILE>) { 10 print; 11 } 12 13 print "Ending processing of file, $_.\n"; 14 }
When I run the code, above, I get this output: (The local directory contains 2 *.txt files: test1.txt and test2.txt.)
Starting processing of file, test1.txt. Line 1 from 'test1.txt' Line 2 from 'test1.txt' Line 3 from 'test1.txt' Use of uninitialized value in concatenation (.) or string at ./test.pl + line 13, <TEST_FILE> line 3. Ending processing of file, . Starting processing of file, test2.txt. Line 1 from 'test2.txt' Line 2 from 'test2.txt' Line 3 from 'test2.txt' Use of uninitialized value in concatenation (.) or string at ./test.pl + line 13, <TEST_FILE> line 6. Ending processing of file, .
Note the missing filenames at the ends of both "Ending processing..." lines, as well as the warnings immediately preceeding them. Here are the contents of "test1.txt" and "test2.txt":
test1.txt:
Line 1 from 'test1.txt' Line 2 from 'test1.txt' Line 3 from 'test1.txt'
test2.txt:
Line 1 from 'test2.txt' Line 2 from 'test2.txt' Line 3 from 'test2.txt'
Thanks!

In reply to $_ getting clobbered by inner loop. by dbanas

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.