#!/usr/local/bin/perl -wT #use strict; #Make sure that all variables are declared before being executed. #Create an array: @myArray = ("Jen Chen", "Robinson Hood", "Donald Duck", "Mickey Mouse"); print "The elements in the array \@myArray are: @myArray\n"; $lastIndex = 0; $lastIndex = @myArray; #This will return the last index in the array. $lastIndex += 1; print "The number of elements in the array \@myArray are: $lastIndex\n"; $lastIndex--; #Now $lastIndex has value of 3. #Now loop thru each element of the array: $count=0; print "\nLooping thru all elements in the \@myArray:\n"; while($count <= $lastIndex){ print "$myArray[$count]\t"; $count++; if($count > $lastIndex){ print "\n"; } } #To add elements into an existing array, we first find the last index of the #array then add the next index element to the array as follow: $myArray[($lastIndex + 1)] = "Jimmy the Great"; $myArray[($lastIndex + 2)] = "Joanne the Great"; $newLastIndex = $#myArray; $count=0; print "\nLooping thru all elements in the \@myArray:\n"; while($count < $newLastIndex){ print "$myArray[$count]\t"; $count++; if($count == $newLastIndex){ print "\n"; } } #Another way to add elements to an existing array is the use of the function # push(Array_name, new_value) as follow: (Note that the new elements are added #to the RIGHT end of the array. To add elements to the left of an array we use #the function unshift(Array_Name, value,...) and shift(Array_Name)). push(@myArray, "Sleeping Beauty"); push(@myArray, "Aladdin", "Walt Disney", "The Golden Fish"); print "\nLooping thru all elements in the \@myArray:\n"; foreach $thing (@myArray){ print "$thing\t"; } print "\n"; #Conversely if we want to remove the elements form an array (from the right end #element) we would use the function pop(Array_name) as follow: $strTmp = pop(@myArray); print "The element removed from the array is: $strTmp\n"; #Since we use quite a bit of the function shift() and unshift(), then we try #out some of them here: unshift(@myArray, "1", "2"); print "\nLooping thru all elements in the \@myArray: after adding 1 and 2 to the \nleft of the array\n"; foreach $thing (@myArray){ print "$thing\t"; } print "\n"; #This is a hash array. %hashArray = ("one",1,"two",2); print "\$hashArray{one} = $hashArray{one}\n"; print "\$hashArray{two} = $hashArray{two}\n";