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
What are Barewords in the Perl Programming Language?
In Perl, "Barewords" refer to unquoted, unescaped, and uninterpolated sequence of characters. Barewords are used for identifiers (such as function names, variable names, etc.), file handles, and certain other special cases. They are subject to specific rules for syntax and interpretation, and may cause unexpected results if not used correctly.
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:
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.
Perl foreach Loop
The foreach loop is a convenient way to loop through an array:
foreach $prez (@presidents) {
print "$prez\n";
}
Definition
In the foreach loop, the scalar referenced after the term foreach is called the control variable and is set to each value of the array as the loop iterates the array.
The join function creates a string with all the elements of the array joined with a string value:
$prezes = join (":", @presidents);
...puts the following into $prezes:
Franklin:Harry:Dwight:John:Lyndon:Richard:Gerald: Jimmy:Ronald:George:Bill
Conversely, the split function will create an array from a list based on a specified separator:
@list2 = split(/:/, $prezes);
Any regular expression may be used for the separator in split.
Also:
push adds an element to the end of the array
pop removes the last element of an array
splice removes one or more elements from the middle of an array
shift removes the first element of an array
# @presidents has 11 elements
push @presidents, "Colin"; # the next president? (12 elements now)
$prez = pop @presidents; # $prez is "Colin" (11 elements now)
$prez = shift @presidents; # $prez is "Franklin" (10 elements now)