eWebProgrammer eweb  

Perl Basics   «Prev  Next»
Lesson 14Perl arrays
ObjectiveLearn how to initialize and access Data in an Array.

Perl Arrays - Initialize and access Data in an Array

Arrays are distinguished by the @ ("at" sign) introducing the name:

You can initialize an array by assigning a list of values to it:
@presidents = ( 'Franklin', 'Harry', 'Dwight', 'John', 
'Lyndon', 'Richard', 'Gerald', 'Jimmy', 
'Ronald', 'George', 'Bill', );

Alternately, you can use barewords with the qw operator:
@presidents = qw( Franklin Harry Dwight John 
Lyndon Richard Gerald Jimmy Ronald George Bill );

Barewords in Perl

Barewords are words that have no other interpretation and are treated as if they were a quoted string.
Now you have an array that contains the first names of some presidents.

Accessing the array elements

The elements in an array are numbered, begining with zero. Each of these numbers is referred to as an index into the array. The array we just defined looks something like this:
The lastname of presidents as elements in a Perl Array
The lastname of presidents as elements in a Perl Array

Once you have the array declared, you can access individual elements with the subscript operator:
$presidents[3]   # John

The number within the brackets is the index into the array. You can use any numeric value to index the array:
$prez_no = 3;
$presidents[$prez_no];    # John

You use a $ here because the value you are extracting from the array is a scalar.
You can use the value of an array even within another string:
print "$presidents[3]\n";

Here are some Perlisms for arrays.

Create Array - Exercise

Click the Exercise link below to write a small program using an array and join.
Create Array - Exercise