Perl Programming/Basic variables

In Perl, there are five different types of variables, each indicated by its own sigil character: scalars ($), arrays (@), hashes (%), subroutines (&), and typeglobals (*). We first introduce scalars, as they are easiest to understand.

Scalar variables
Although they have a complicated name, a scalar variable is just a way of storing a value for later use. For example, consider:

If we wanted to change the name of the user, we can just change the string. However, if this program were hundreds of lines long and the name was used several times, trying to find the strings throughout the program would be more fuss than it was worth. Instead, it is common to use variables for any values that might change.

This new program gives exactly the same output as the previous one. There are several new things about this program, the most obvious being the line


 * my $firstname = "John";
 * my Tells the perl interpreter to give you a new variable. Technically, this is optional but highly recommended.
 * $firstname Tells the perl interpreter that you want a scalar variable called firstname
 * = Tells the perl interpreter to assign the value on it's right hand side to the variable on the left hand side
 * "John" Tells the perl interpreter that every time you use $firstname you want it to use the string John.

While using variables to contain information that you have programmed is all very well, variables are used to store data that can change while your program runs, as their name implies.

You should notice that when we change the value of $firstname we do not need to use the my operator. This is because we have already told perl to give us the variable, and it is now ours to do what we wish with.

Numbers
Now, while strings are very useful, there is a place in computer programs for numbers as well. A scalar variable can contain either a number or a string.

Perl does not provide any easy way of telling the type of information stored in a scalar variable. Indeed, if you give Perl a string and ask it to do number operation, Perl will automatically convert the string into the number; and vice versa. Here is an example:

If you run this program, you can see that both the first two examples result in 11 being stored to $y. Perl does not convert English words to numbers, though, and if you give a string like <tt>"ten"</tt> it will not turn it to 10, but instead just think it is 0. The last example shows that it actually tries to understand the string as a number, and stops whenever it finds something it doesn't understand.

Raw printing
It is of course possible to output variables without including them in a string.

Exercises
Perl/Variáveis escalares