< Perl Tutorial

Perl variables

← Previous Next →

Perl Variables

Variables in Perl are the reserved memory locations that can be sued to store any value. This simply means that whenever we create a new variable we reserve some memory space for use. By assigning different data types to variables, we can store integers, decimals, or strings in these variables as the Perl Interpreter allocates memory and decides what can be stored in that type of memory depending the dat type of the variable.
Perl has three basic data types:

  • Scalars
  • Arrays
  • Hashes

For these three data types there are three different kinds of variables. A scalar variable will precede by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will precede by at sign (@) and it will store ordered lists of scalars. Finaly, the Hash variable will precede by percent sign (%) and will be used to store sets of key/value pairs.

Perl maintains every variable type in a separate namespace. So we can use the same name for a scalar variable, an array, or a hash without any fear of conflict. This means that $variable and @variable are two different variables.

Scalar Variables

A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire page. We can store anything in a scalar variable just keeping in mind the fact that it must at any case be a single entity.
Following examples show some Scalar variables:

$var1 = 2254;               # An integer assignment
$var2 = "Just a String";    # A string 
$var3 = 1245.625;           # A floating point

Array Variables

An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign.
Following example shows some Array type variables:

@numbers = (25, 30, 40);             
@strings = ("John Paul", "Lisa", "Kumar");

Hash Variables

A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. 
An example of Hash variable creation is:

%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40);
← Previous Next →