Hi Monks

Can anyone explain why the code below destroys the contents of @test_array?

All I can see is that we are simply reading from @test_array and never editing it, if the while statement in the subroutine is changed to a

foreach $line (<IN>)

@test_array remains unaffected.

I'm baffled, should the $_ variable being used for the file not be in a different scope to @test_array?

The size of @test_array remains unaffected but each element is empty, thus the warnings for uninitialised variables.

please say its not something blatantly obvious!!!
Orthanc

#!/usr/local/bin/perl -w my @test_array=( 'Element1', 'Element2', 'Element3', 'Element4', 'Element5', ); foreach (@test_array) { print "\"$_\"\n"; do_something(); } print "\n"; foreach (@test_array) { print "\"$_\"\n"; } sub do_something { open(IN, "$0") || die("No file"); while (<IN>) { # Do nothing, in the real software we would do something # with the content. } close(IN); }

In reply to What Is Going On Here ????? by orthanc

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.