Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I create a variable whose name depends on the value of another?

Status
Not open for further replies.

jtb1492

Technical User
Mar 17, 2005
25
0
0
US
I'd like to have a array with names in it, like 'Blue' and 'White' and 'Green'. Then I want to be able to create scalar variables from within some loops like:

$AWhiteBig
$BWhiteBig
$AWhiteSmall
$BWhiteSmall
$ABlueBig
$BBlueBig

etc.....

The loops I don't have a problem with. But how do I tell perl to create those variables?

Thanks!

Jason
 
Echch! Dynamic variable names. Someone give me a can opener, I think theres a can of memory pointers around here somewhere.

Alchemy is easy with Perl!
s/lead/gold/g;
 
when I see questions like this, I wonder if all you don't need is to use a hash instead of trying to make dynamic variables.
 
Excellent answer KevinADC. Exactly what I would suggest.
Instead of:
Code:
$AWhiteBig
$BWhiteBig
$AWhiteSmall
$BWhiteSmall
$ABlueBig
$BBlueBig
You have:
Code:
$hash{'AWhiteBig'};
$hash{'BWhiteBig'};
$hash{'AWhiteSmall'};
$hash{'BWhiteSmall'};
$hash{'ABlueBig'};
$hash{'BBlueBig'};
That is much better, cleaner and will run hapilly under "use strict" whereas soft references will not.
It then becomes trivial to use a scalar for the key names:
Code:
$hash{$varName};


Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top