Making your code work is as easy as using curly braces instead of parenthesis:

for( $a = 1; $a <= 10; $a++ ) { ${'var_' . $a} = 5 + $a; } print $var_1, "\n"; print $var_10, "\n";

But this isn't really what you want.

This is called a symbolic reference, and is outlawed by strict 'refs', because of how easy it is to make a grave mistake when mingling data with code in such ways. It could be that you have one of those truly rare situations where it's necessary, but if you don't (and if you have to ask how, you probably don't), it's best to use an array or a hash instead, or hard references, or a combination thereof.

Please read the following articles:

Perl allows you to do really dangerous (and possibly stupid) things if you want, because it doesn't want to get in the way of doing something really amazing when you need to be amazing. But usually you don't need to be amazing, and don't need the risk associated with such death-defying feats of amazingness. For the 99.9% of the time when you don't need to be a dare-devil, Perl provides you with hashes, hard references, and arrays. The global symbol table (the thing you're manipulating when you use a variable as a variable name) is, itself, a form of a hash. If a hash is good enough for Perl, it's probably good enough for your uses too. ...though in this case I'd be inclined to favor an array since you're just numbering your elements anyway.


Dave


In reply to Re: Concatenation on Varibale Name by davido
in thread Concatenation on Varibale Name by dushyant

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.