Why is it not possible for scalar package variables, but possible for array package variables?

I'll answer that myself:

*foo{THING} returns undef if that particular THING hasn't been used yet, except in the case of scalars. *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release.
And let me point out that this is from the perlref man page. It shows how to access "global" (package-based) variables through the symbol table.

For the OP and others, pardon me while I give some references to things in various posts on the thread. Follow up the presentation with the documentation of those concepts.

Farther down on that page is "symbolic references", which are also useful in this situation. That is, given a string $s that contains "var1" and use $$s to refer to $var1. You can't tell the difference between the variable existing but holding undef, or not previously existing. That's the general problem here. But, if your variables aren't undef, you might not have to worry about that.

It also shows ${"${pack}::$name"} = 5; which doesn't use eval. However, the use of eval in another post wasn't really to access it, but to get a compile-time error if a variable was used without being defined.

But... I agree that you should not do that. These tricks are for meta-programming, to write such things as package importers. For normal code, don't use a namespace as a hash.

—John update: picky nomenclature.


In reply to Re^4: Using a sting with a variable name by John M. Dlugosz
in thread Using a sting with a variable name by bingohighway

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.