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 strongm 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 use the contents of a variable as the name for another variable?

Little tricks

How do I use the contents of a variable as the name for another variable?

by  MikeLacey  Posted    (Edited  )
This very easy to do in Perl but that doesn't mean you should do it; you probably (almost certainly) shouldn't.

You can do it like this.

$v = 'myscalarvar';
$$v = 1; # same as saying $myscalarvar = 1

But don't do it.

What if you have code like this:

$x = 'hello';
$z = 'x';
$$z = 'goodbye';

What's the value of $x at the end of that?

Use a hash instead - like this:

$mylist{arrive} ='hello';
$mylist{leave} ='goodbye';
$mylist{wait} ='slouch';

That will do exactly as you want and won't collide with other variables.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top