Perl - Manipulating Arrays
In a Nutshell - CIW Course Section 2, Part B1, Chapter 6
Sorting Arrays
The sort function will accepts an array of values as an argument, and will arrange the elements in alphabetic order for string values or in numeric order for numerical values. The sorted list is the output of the function and must be assigned to an array or directed to the screen.
@names = ("Tom", "Dick", "Harry");
@newNames = sort(@names);
print ("@newNames\n");
In this example the names are sorted alphabetically and assigned to the @newNames array. The original @names array remains unchanged.
The sort order can be changed by adding a block of comparison code using the comparison operators "<=>" for numeric values or "cmp" for string values.
{$a <=> $b}
{$a cmp $b}
The $a and $b variables are are special variables representing adjacent values in the array to be sorted. In the above examples $a is before $b so the sort order will be ascending, the default.
@newNames = sort({$b cmp $a} @names);
By using the comparison code with the $b before the $a, as above, the array will be sorted in descending order.
FOREACH Statement
Earlier we used a for loop to iterate through the elements of an array. A more elegant approach is the foreach statement.
@names = ("Tom", "Dick", "Harry",
"Fred", "Wilma", "Barney",
"Betty");
foreach(@names)
{
print("$_\n");
}
This iterates through each element and uses the special variable "$_" to identify the current element.
PUSH and POP functions
Push and pop will add or remove elements to or from the end of an array. The push function can add multiple values, the pop function will remove only one. The pop function will return the removed value as it's output.
@names = ("Tom", "Dick", "Harry");
push(@names, "Fred", "Wilma");
print("@names\n");
Output: Tom Dick Harry Fred Wilma
The two new names have been added to the end of the array.
@names = ("Fred", "Wilma", "Barney",
"Betty");
$lastName = pop(@names);
print("$lastName\n");
Output: Betty
The pop function returns the name "Betty" which has now been removed from the array.
SHIFT and UNSHIFT functions
Unshift and shift will add or remove element from the beginning of an array. The unshift function can add multiple values, the shift function will remove only one. The shift function will return the removed value as it's output.
I will not include examples here, as these function operate in the same manner as push and pop.

