"Sputnik" help  
Sputnik Help
Language Reference - Variables - Variable Variables

Before we begin make sure you have read and understand the Variables section.

Variable variables are somewhat complicated to use, and even more complicated to explain, so you might need to reread this section a few times before it makes sense. Variable variables allow you to access the contents of a variable without knowing it's name directly - it's like indirectly referring to a variable.Consider this piece of code:

my $bar = 10;
my $foo = "bar";
There are two ways we can output the value of $bar here. We can either use print $bar, which is quite straightforward, or we can take advantage of the concept of variable variables, and use print $$foo;. That's right - two dollar signs.

By using $$foo, Sputnik will look up the contents of $foo, convert it to a string, then look up the variable of the same name, and return its value. In the example above, $foo contains the string "bar", so Sputnik will look up the variable named $bar and output its value - in this case, 10.

Variable variables are fairly clumsy to use, but they can be helpful when you are stuck. Furthermore, they only really get more clumsy the more indirection you use. For example, this next script outputs "Variable!" four times, but I hope you agree it is not very easy to read!

my $foo = "Variable!\n";
my $bar = "foo";
my $wom = "bar";
my $bat = "wom";
print $foo;
print $$bar;
print $$$wom;
print $$$$bat;
// Variable!
// Variable!
// Variable!
// Variable!


Cheryl (uberfox@hotmail.com)