2.1.2 Assigning A Variable

A very useful operator is the assignment operator. It requires a variable name to the left and a value to the right. In Perl, a scalar variable’s name starts with a $ in front. Thus, $temperature is a scalar variable name in Perl. So, is $friend. We can assign values to scalar variables using the assignment operator =.

$temperature = 30;
$friend = "Justin O'Malley"

The assignment operator associates a value with a variable. Thus, after these assignments, whenever we use $temperature in an expression or statement, its value is taken to be 30. Similarly, the value of $friend is taken to the string "Justin O'Malley". Perl makes no distinction whether a scalar is a string or a number. Thus, if we want, we can make the following assignments as well.

$temperature = "30 degrees Fahrenheit";
$temperature = '30F';

Here, $temperature is given a string value as opposed to the earlier assignment to a numeric value. Perl does not care whether the value given to a scalar is numeric or string. However, we should be careful whether a scalar is a string or a number. This is because the operators that we see a little later works differently with strings and integers. Perl coerces or converts a string to a number if needed and vice versa. Here x is the string repetition operator we see later.

Thus, when we write

01 x 20

Perl converts 01 into the string "01" and repeats it 20 times to form 

0101010101010101010101010101010101010101

because x expects a string operand on the left. Here x is the string repetition operator we see in Section 2.1.3.2. Since it does not get a string, it converts the number to a string by putting quotes around it. Similarly, if we write

2 + "a23b4"

Perl converts the string "a23b4" to a number by trying to salvage something out of the string. It scans the string from left to right and picks out the first substring of contiguous digits and converts the substring to a number. Here, from the string "a23b4", it picks the substring "23" and uses it as the number 23. Thus, the result of the addition is 25.