Variable Variables
Get introduced to variable variables in this lesson and learn how you can use them in Perl.
We'll cover the following
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:
$vehicle = "car"; # vehicle has value "car"$$vehicle = "honda"; # car has value "honda"print "\$vehicle:\t";print $vehicle; #prints carprint "\n";print "\${\$vehicle}:\t"; # using \ as $ is special characterprint ${$vehicle}; #prints hondaprint "\n";print "\$\$vehicle:\t";print $$vehicle; #prints hondaprint "\n";print "\$car:\t\t";print $car; #prints hondaprint "\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:
$skyColor = 'Blue';$varPrefix = 'sky';print "\$skyColor:\t\t";print $skyColor; # Outputs "Blue"print"\n";print "\${\$varPrefix . 'Color'}:\t";=PODvarPrefix will give value sky and the dot operator concatenatesit with Color hence making it skyColor.Putting $ before skycolor makes it a variable variable.=cutprint ${$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:
${$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
What will be the output of the following code?
$fruit = "Mango";
$$fruit = "yellow";
print "The color of ", $fruit , " is " , $Mango ;
Compile time error
The color of fruit is yellow
The color of Mango is yellow