Variable Variables

Get introduced to variable variables in this lesson and learn how you can use them in Perl.

What are variable Variables?

Using Perl, we can access data through dynamic variable names. The name of a variable can be stored in another variable, allowing it to be accessed dynamically. Such variables are known as variable variables.

To turn a variable into a variable variable, you put an extra $ sign in front of your variable. This method is illustrated in the following figure:

Note: Variable name, say $vehicle, can be put between {}.We will see its usage in the next section.

Implementation

The following code snippet shows how this is done in Perl:

Press + to interact
$vehicle = "car"; # vehicle has value "car"
$$vehicle = "honda"; # car has value "honda"
print "\$vehicle:\t";
print $vehicle; #prints car
print "\n";
print "\${\$vehicle}:\t"; # using \ as $ is special character
print ${$vehicle}; #prints honda
print "\n";
print "\$\$vehicle:\t";
print $$vehicle; #prints honda
print "\n";
print "\$car:\t\t";
print $car; #prints honda
print "\n";

The following example shows two different ways of accessing a variable’s value: directly and using variable variables. It displays the text “Blue” on the screen using both ways:

Press + to interact
$skyColor = 'Blue';
$varPrefix = 'sky';
print "\$skyColor:\t\t";
print $skyColor; # Outputs "Blue"
print"\n";
print "\${\$varPrefix . 'Color'}:\t";
=POD
varPrefix will give value sky and the dot operator concatenates
it with Color hence making it skyColor.
Putting $ before skycolor makes it a variable variable.
=cut
print ${$varPrefix . 'Color'}; # Also outputs "Blue"

Using {} is only mandatory when the name of the variable is itself an expression and . operator is used to concatenating it with other variables part to get the result, like this:

Press + to interact
${$variableNamePart1 . $variableNamePart2} = $value;

Don’t worry about the (.) operator, we’ll discuss that in details in the string chapter.

It is nevertheless recommended to always use {} because it’s more readable.

Quick quiz

Q

What will be the output of the following code?

  $fruit = "Mango";
  $$fruit = "yellow";
	print "The color of ", $fruit , " is "  , $Mango ;
A)

Compile time error

B)

The color of fruit is yellow

C)

The color of Mango is yellow