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:
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:
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:
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