![]() |
||
|
Lesson 14
Objective
|
Perl arrays
Learn how to initialize and access data in an array. |
|
|
Arrays are distinguished by the @ ("at" sign) introducing the name:
Barewords in Perl
@presidents
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', ); @presidents = qw( Franklin Harry Dwight John Lyndon Richard Gerald Jimmy Ronald George Bill );
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:
$presidents[3] # JohnThe 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 |
||
|
|
||

