All programming languages support variables. Variables are like string literals, except that they hold a specific value or values. Perl has three sets of variables that it supports.
As mentioned above, scalar values are used to track a single piece of information. Perl's most commonly used variable is the $_, this is the default variable for perls many functions, so become very familiar with it.
We can see a value being assigned to a scalar value in the following example along with interpolation.
$var="my Scalar Variable";
$sentence = "This is $var";
The output of the above code would be : This is my Scalar Variable
Arrays hold a list of variables and are handled in a variety of different ways. You can give the values to the array during initialization:
@array=('one','two','three');
The above array assigns three values into the array, the values are seperated by commas. The first subscript of an array is always 0 unless you change it with special variable $[ . This is generally not good practice because you can confuse people reading you code. In order to read the value You would refer to the array name and the subscript that you want. If we wanted the value 'two' we would say:
print "$array[1]";
We say $array because we are referring to only one value, followed by open braket, the subscript that you want and then the close bracket. This would return the second value in your array.
Hashes can be initialized in a similar manner to arrays.
%hash=('key1','value1','key2','value2','key3','value3');
The major difference is that you have to place the values in a key-value order. So the first value you type would be the key and the second the actual value, the third the key and the fourth the value associated with that key. In order to retrieve the value from hash, we would do it similarly to an array except that instead of using [ ] we would use { }, and instead of the subscript number we would use the key. If we wanted to retrieve 'value2'. We would do the following.
print "$hash{'key2'}";
Be aware that perl variables are case sensative and that $me and $Me and $mE and $ME are four seperate variables. Also, if you have a scalar variable called $me and an array called @me and a hash called %me. They are three seperate variables, and not the same one.
![]() |
![]() |
![]() |