I need help with my and scope. Management asked I audit someone else's code, and I came across what I thought was a problem with a variable going out of scope.

I wrote the following as a test, and to my surprise, it ran without errors! Now I'm really confused.

use strict; use warnings; sub scope_test() { my @test_array = (1, 2, 3, 4, 5, 6); return \@test_array; } print join ("\n", @{ scope_test() } );

I thought that @test_array was local to the function, so it would need to copy the data before returning a value. I thought that returning a reference to that variable would cause a problem, but it doesn't.

What's going on here? Am I crazy? Am I biased because C/C++ behaves differently with scope? Or am I complete wrong about scope in the first place, and it works this way in both Perl and C/C++? There's no style guide here, and sometimes I have a problem differentiating between "different from how I'd do it" and "wrong."

Thanks in advance for any help.

Edit: Updated the title for better search results later


In reply to my, scope, and references by chayashida

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.