eWebProgrammer
Distributednetworks GofPatterns
prev prev
Course navigation
Arrays in Perl
Perlisms for arrays
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:
  1. push adds an element to the end of the array
  2. pop removes the last element of an array
  3. splice removes one or more elements from the middle of an array
  4. 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)
Course navigation