Contents / Previous / Next


Variables and Data Types

Perl has three main variable types: scalars, arrays, and hashes.
Perl's datatypes are well documented in perldata (man perldata).


Scalar variables: $

The most basic kind of variable is a Scalar, it starts with a $: Examples:
$var = 9;
$var = 'high';

Scalar values can be strings, integers or floating point numbers. Perl will automatically convert between them as required, so there is no need to pre-declare variable types.
Perl also accepts numbers as strings, and does arithmetic and other operations in the same way:

$x = '0.9';
$y = '0.07';
$z= $x + $y;
print '$x + $y = $z';
print "\t$x + $y = $z\n";
#
# Output: $x + $y = $z	0.9 + 0.07 = 0.97

The double quotes force the interpretation of codes (here: \n, \t), and variables.

Variable names can consist of numbers, letters and underscores, but they should not start with a number.

You can use {} (curly braces) to clarify precedence, e.g., ${...}, &{...}, $$p is a shorthand for ${$p}.


Arrays: @, $[]

An array represents a list of values:
my @animals = ("camel", "llama", "owl");
my @numbers = (23, 42, 69);
my @mixed   = ("camel", 42, 1.23);

my @animals = qw/camel, llama, owl/;

Lists (list value constructors) are denoted by separating individual values by commas (enclosed in parentheses where precedence requires it):

  (LIST)
Lists are used to assigns a list of value to an array variable.

Arrays are zero-indexed. The $ (dollar sign) refers to one element of the array, used in conjunction with [ ]:

print $animals[0];   # prints "camel"
print $animals[1];   # prints "llama"

The special variable $#array gives the index of the last element of an array:

print $mixed[$#mixed]; # last element, prints 1.23
"$#array + 1" is the number of items in an array. Also using @array where Perl expects to find a scalar value ("in scalar context") will give the number of elements in the array:
@a = ( 7, 9, "camel" );
$e = @a;

print "$#a+1 == $e : @a\n";
# Output: 2+1 == 3 : 7 9 camel
This is useful in loops or conditional statements:
if (@animals < 5) { ... }

The @ (at sign) refers to the entire array or slice of an array when used in conjuction with [ ]:

@animals[0,1];   # gives ("camel", "llama");
@animals[0..2];  # gives ("camel", "llama", "owl");
@animals[1..$#animals];  # all except the first element

# assign elements 3 to 5:
my @animals[3..5] = qw/camel, llama, owl/; 

Displaying arrays works with print:

print @animals;	    # By itself
print "\n";
print "@animals";   # Embedded in double quotes
print "\n";
print @animals."";  # In a scalar context
Since context is important, the above examples produce different results:
camelllamaowl
camel llama owl
3


Hashes = Associative Arrays = Maps: %, =>

A hash represents a set of key/value pairs.
The % (percent sign) refers to the entire hash:
my %fruit_color = ("apple", "red", "banana", "yellow");

  or 

my %fruit_color = (
    apple  => "red",
    banana => "yellow",
);

The { } (braces) are used to denote the key and $ with { } to get the value of the array element indexed on the key:

$fruit_color{"apple"};   # gives "red"

You can get at lists of keys and values with "keys()" and "values()".
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;

Hashes have no particular internal order, though you can sort the keys and loop through them.


References: \

A reference is a scalar value and can refer to any other Perl data type. Examples:
$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&handler;
By storing a reference as the value of an array or hash element, you can easily create arrays and hashes within arrays and hashes (man perlref).


Filehandles: <>

You can read from an open filehandle using the "<>" operator:
Examples: <STDIN>, <STDOUT>, <STDERR>, <MY_FILE>.
Where MY_FILE is a user-specified handle.


Examples: Accessing Variables

$var a simple scalar variable.
$var[28] 29th element of array @var.
$p = \@var now $p is a reference to array @var.
$$p[28] 29th element of array referenced by $p.
Also, $p->[28].
$var[-1] last element of array @var.
$var[$i][$j] $jth element of the $ith element of array @var.
$var{'Feb'} one value from hash (associative array) %var.
$p = \%var now $p is a reference to hash %var.
$$p{'Feb'} a value from hash referenced by $p.
Also, $p->{'Feb'}.
$#var last index of array @var.
@var the entire array; in a scalar context, the number of elements in the array.
@var[3,4,5] a slice of array @var.
@var{'a','b'} a slice of %var; same as ($var{'a'},$var{'b'}).
%var the entire hash; in a scalar context, true if the hash has elements.


Variable scoping: "my"

"my" creates lexically scoped variables:
my $var = "value";
The variables are scoped to the block or function-block (surrounded by curly-braces) in which they are defined.

Without the keyword "my" a global variables is created.

$var = "value";