It hasn't yet been said in this thread, and should have been: Don't try to do what you're trying to do.

The advice to use a hash is the obligatory right answer under most situations where you might be tempted to create variable names on the fly, at runtime.

What you're trying to do, in your specific case, is create a symbolic reference, or a soft reference. A symbolic (or soft) reference, in Perl, is where you use some value (computed or stored in a variable) to indicate the name of a variable. Perl lets you do this (if you use the right syntax, and if you don't use strict;). Don't be tempted to use this "feature" of Perl, until you're intimately familiar with the reasons why you shouldn't use this feature.

Almost always, it's better to use a hash, or hard references, or some combination of the two. The fact is that the package global namespace really is just a glorified hash anyway. If that's good enough for perl (the executable), it's probably good enough for you too... but don't muck around with your program's package global namespace hash (Ugh, what a mess that would be!)... use your own hash to hold these dynamic names. Treating your package global namespace like a symbolic scratchpad is sooner or later (probably sooner) cause you a lot of headaches in the form of hard-to-find bugs, latent bugs, variable collisions, and so on. As merlyn once said, "If you're just here to watch the play, stay out from behind the curtain." (that's from memory, so it may be a little less than a direct quote)


Dave


In reply to Re: Dynamic variables by davido
in thread Dynamic variables by xspikx

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.