Perl Variables
A variable is nothing more than a name given to a particular area in memory that stores a value created by a Perl program. A variable that stores a single value in Perl starts with a '$' sign and must be followed by a letter or underscore, then any combination of letters, numbers and underscores can be used thereafter, up to 255 characters. Variable names are also case-sensitive. Unlike some languages, for example C#, Perl is a loosely typed language, which means that when a variable is declared, a datatype does not have to be assigned. A variable is automatically converted to the correct datatype depending on the value that is assigned to it.
When creating a variable, it takes the following format. The equals sign between the variable name and value is known as an assignment operator and will be discussed further in the next section on operators.
my variable_name = value
It should be noted that the 'my' reserved word is only necessary when declaring variables if a 'use strict' statement, discussed previously, is present. Reserved words have a specific meaning and cannot be used for anything else. They are shown in blue on the preceding and following pages.
Below are some example variables.
# Integer variable. my $exampleInteger = 5; # Floating point or decimal number variable. my $exampleFloat = 5.1; # String variable. my $exampleString = "This is a string";
The values of variables can be displayed, for example, in the terminal, using the 'print' function. The '\n' is known as an escape character and is used to create a new line.
print "$exampleInteger\n"; print "$exampleFloat\n"; print "$exampleString\n";
This will display the following in the terminal.
5 5.1 This is a string
Values of variables can also be displayed as part of a longer string.
print "Value of \$exampleInteger: $exampleInteger\n"; print "Value of \$exampleFloat: $exampleFloat\n"; print "Value of \$exampleString: $exampleString\n";
A '\' is placed in front of the variable names above in order to 'escape' the dollar sign so that the name is displayed literally, rather than its value.
Value of $exampleInteger: 5 Value of $exampleFloat: 5.1 Value of $exampleString: This is a string
The variables discussed above, which store a single value, are known as scalar variables in Perl. There are also array and hash variables in Perl, which can store multiple values. These are discussed separately.