Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Concatenation on Varibale Name

by davido (Cardinal)
on Oct 17, 2012 at 17:42 UTC ( [id://999585]=note: print w/replies, xml ) Need Help??


in reply to Concatenation on Varibale Name

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://999585]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-03-19 05:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found