I'm confused because I thought when using "strict", variables only existed inside their blocks

Using the strict pragma doesn't actually change where variables "exist" (as you put it.) What it does do is force the program to error out when a global variable is used without being properly declared. Variables declared with my are lexically scoped (not global) and are only visible to their enclosing block, file, or eval.

When I pass the reference to %sub_hash back from &makehash, why isn't it a reference to something that no longer exists?

It is probably easiest and most correct to think of the reference as a new value. It is also best to think of your variable's value and its name being separate. Your my %sub_hash variable is indeed only visible within your subroutine. That is to say, the value it holds can only be accessed via the name %sub_hash while inside your sub. If you did not pass a reference to the value back to the main program, there would be no way to get at that value again (and perl would consider it ripe for garbage collecting.) Since you do create a reference to the value by using the backwhack ("\") operator, perl makes a note of the fact that you still want it to be accessible (by incrementing its reference count) and will not garbage collect it.

Does that help?

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: What's a reference? What's a variable? What's scope? by sauoq
in thread What's a reference? What's a variable? What's scope? by kurt_kober

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.