Perl Information Center Tutorials - Variables
These tutorials were written to help you get a quick, but thorough, understanding of Perl -
the scope of the language as well as it's specific capabilities.
| Beginners
| Built-In Functions
| Advanced
| CGI Applications
|
|
|
|
|
|
Variables
Like all languages, Perl uses variables to store values. In Perl all
variables, without exception, begin with one of three characters:
- $ - defines a scalar (string, integer, floating point number)
- @ - defines an array
- % - defines a hash
The meanings of scalar, array and hash are generally well known, and
will be discussed in more detail in the tutorial on
data types.
Variable Names
Variable names (the part behind the $, @, and %) must consist of
letters (a-z), numbers (0-9), or the underscore character. These
are all valid variable names:
$a
$47
@dog2
@1down
%my_hash
%MyHash
Special Characters
Just so you won't be too confused when you see it, Perl also allows
other special characters (such as ^ or &) to be used in single character
variable names. Perl reserves most of these for its use so you won't
be creating such variable names yourself.
Two such single character, pre-defined variable names are:
$_ default variable for built-in functions
@_ array containing arguments passed to a subroutine
Perl also pre-defines many other variables, which are discussed
in other sections of this tutorial. Two such examples are:
@ARG array containing command line values
%ENV environmental values passed to Perl by web server
Case Sensitivity
Perl is case-sensitive. The variables $dog and $DOG are
two different variables.
Creating a Variable
Unlike some languages which require that you define a variable before
using it, Perl allows you to define a variable by simply using it in
a line of code.
$a = 5 # $a is created by assigning it a value
my $b = 2 # the tutorial on scope discusses 'my'
When a variable has not yet been assigned a value, Perl sets the value to undef,
which is similar to NULL in other languages. The Perl defined function can test
to see if a variable has been assigned a value.
NameSpace
Note that $x, @x, and %x are different variables. They can coexist.
These lines of code will create all three variables, which Perl maintains
separately.
$x = 2 # scalar
@x = (1,2) # array
%x = ("a",1,"b",2) # hash
Good Practice
Using variable names which describe the content of the variable is
considered good practice. For example, $size is preferred over $s.
Programmer's also use the following two common variable naming practices,
both of which involve using more than one word in the variable name.
last_index # words separated by an underscore
LastIndex # capitalizing words in the variable name
|