Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: Concatenation on Varibale Name

by davido (Archbishop)
on Oct 17, 2012 at 17:42 UTC ( #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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://999585]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2017-01-16 12:11 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (150 votes). Check out past polls.