New Document
PERL - Array Variables

Arrays are a special type of variable that store list style data types. Each object of the list is termed an element and elements can either be a string, a number, or any type of scalar data including another variable.

Place an array into a PERL script, using the at symbol (@).

perlarrays.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# PRINT THE ARRAY
print "@coins";
print "<br />";
print @coins;

Check the syntax here. We printed the same array twice using quotes around the first line. Notice how the line with quotes around it prints nicely to the browser leaving spaces between each word. PERL does this automatically as it assumes the quotations are meant for a string and strings are usually comprised of words that require spacing between each word.

PERL - Array Indexing

Each element of the array can be indexed using a scalar version of the same array. When an array is defined, PERL automatically numbers each element in the array beginning with zero. This phenomenon is termed array indexing.

arrayindexing.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# PRINT THE WHOLE ARRAY
print "@coins";

# PRINT EACH SCALAR ELEMENT
print "<br />";
print $coins[0]; #Prints the first element
print "<br />";
print $coins[1]; #Prints the 2nd element
print "<br />";
print $coins[2]; #Prints the 3rd element
arrayindexing.pl:

Quarter Dime Nickel
Quarter
Dime
Nickel

Elements can also be indexed backwards using negative integers instead of positive numbers.

arrayindexing2.pl:
#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

# DEFINE AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# PRINT THE WHOLE ARRAY
print "@coins";

# PRINT EACH SCALAR ELEMENT
print "<br />";
print $coins[0]; #Prints the first element
print "<br />";
print $coins[-1]; #Prints the last element
print "<br />";
print $coins[-2]; #Prints 2nd to last element
arrayindexing2.pl:

Quarter Dime Nickel
Quarter
Nickel
Dime
PERL - The qw Subroutine

Quotations can be a hassle, especially if the array you wish to build has more than 5 elements. Use this neat little subroutine to remove the need for quotes around each element when you define an array.

PERL Code:

#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

# DEFINE AN ARRAY WITHOUT QUOTES
@coins = qw(Quarter Dime Nickel);
print "@coins";
Display:

Quarter Dime Nickel
PERL - Sequential Number Arrays

PERL offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like this:

sequentialarrays.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

# SHORTCUTS SAVE TIME
@10 = (1 .. 10);
@100 = (1 .. 100);
@1000 = (100 .. 1000);
@abc = (a .. z);

# PRINT 'EM TO THE BROWSER
print "@10<br />";
print "@100<br />";
print "@1000<br />";
print "@abc<br />";
PERL - Finding the length of an Array

Retrieving a numerical value that represents the length of an array is a two step process. First, you need to set the array to a scalar variable, then just print the new variable to the browser as shown below.

There are two ways to set an array to scalar mode. We can use the scalar() function or we can redefine the array as a scalar variable.

findlength.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n";	#HTTP HEADER

@nums = (1 .. 20);
@alpha = ("a" .. "z");

# SCALAR FUNCTION
print scalar(@nums)."<br />";
print scalar(@alpha)."<br />";

# REDEFINE TO SCALAR
$nums = @nums;
$alpha = @alpha;

print "$nums<br />";
print "$alpha<br />";
print "There are $nums numerical elements<br />";
print "There are ".scalar(@alpha)." letters in the alphabet!";
findlength.pl:

20
26
20
26
There are 20 numerical elements
There are 26 letters in the alphabet!

Setting our array to a scalar data type transformed our array into scalar data. As a result PERL is forced to count through each element and return a value representing the array.

PERL - Adding and Removing Elements

Adding elements is a breeze, we use the following functions to add/remove and elements:

  • push() - adds an element to the end of an array.
  • unshift() - adds an element to the beginning of an array.
  • pop() - removes the last element of an array.
  • shift() - removes the first element of an array.

When adding elements using push() or shift() you must specify two arguments, first the array name and second the name of the element to add. Removing an element with pop() or shift() only requires that you send the array as an argument.

modifyarrays.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# AN ARRAY
@coins = ("Quarter","Dime","Nickel");

# ADD ELEMENTS
push(@coins, "Penny");
print "@coins";
print "<br />";
unshift(@coins, "Dollar");
print "@coins";

# REMOVE ELEMENTS
pop(@coins);
print "<br />";
print "@coins";
shift(@coins);
print "<br />";

# BACK TO HOW IT WAS
print "@coins";
modifyarrays.pl:

Quarter Dime Nickel Our original Array, 3 elements.
Quarter Dime Nickel Penny Add penny to the end.
Dollar Quarter Dime Nickel Penny Add Dollar to the beginning.
Dollar Quarter Dime Nickel Remove Penny.
Quarter Dime Nickel Remove dollar, back to the original!
Array Functions:
FunctionDefinition
push(@array, Element)Adds to the end of an array
pop(@array)Removes the last element of the array
unshift(@array, Element)Adds to the beginning of an array
shift(@array)Removes the first element of an array
delete $array[index]Removes an element by index number

It is also possible to remove any element by its indexed number. Just remember to use the scalar form of the array when doing so.($)

PERL - Slicing Array Elements

There is no specific slice() function for slicing up elements of an array. Instead PERL allows us to create a new array with elements of another array using array indexing.

slicendice.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

@coins = qw(Quarter Dime Nickel Penny);
@slicecoins = @coins[0,2];
print "@slicecoins\n";
print "<br />";

When handling lists of sequential numbers, the range operator can quickly become your favorite tool for slicing up arrays.

myrangefriend.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# SEQUENTIAL ARRAY
@nums = (1..200);
@slicenums = @nums[10..20,50..60,190..200];
print "@slicenums";
myrangefriend.pl:
11 12 13 14 15 16 17 18 19 20 21 51 52 53 54 55 56 57
58 59 60 61 191 192 193 194 195 196 197 198 199 200
PERL - Replacing Array Elements

Replacing elements is possible with the splice() function. Splice() requires a handful of arguments and the formula reads: splice(@array,first-element,sequential_length,name of new elements).

Essentially, you send PERL an array to splice, then direct it to the starting element, count through how many elements to replace, and then fill in the missing elements with new information.

replacewithsplice.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP Header

@nums = (1..20);
splice(@nums, 5,5,21..25);
print "@nums";

Take note of the fact that the actual replacement begins after the 5th element, starting with the number 6 in the example above. Five elements are then replaced from 6-10 with the numbers 21-25. Let the "Ooohing" and "Ahhhing" begin."

PERL - Transform Strings to Arrays

With the split function, it is possible to transform a string into an array. To do this simply define an array and set it equal to a split function. The split function requires two arguments, first the character of which to split and also the string variable.

stringtoarray.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# DEFINED STRINGS
$astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$namelist = "Larry,David,Roger,Ken,Michael,Tom";

# STRINGS ARE NOW ARRAYS
@array = split('-',$astring);
@names = split(',',$namelist);

# PRINT THE NEW ARRAYS
print @array."<br />";
print "@names";
split.pl:
Rain Drops On Roses And Whiskers On Kittens
Larry David Roger Ken Michael Tom

Notice you have to send the split function where the split will occur. In the first example, the split was called at each hyphen. In the latter example the names were split by a comma, allowing for the split to take place between each name.

Likewise, we can use the join() function to rejoin the array elements and form one long, scalar string.

arraytostring.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# A COUPLE OF ARRAYS
@array = ("David","Larry","Roger","Ken","Michael","Tom");
@array2 = qw(Pizza Steak Chicken Burgers);

# JOIN 'EM TOGETHER
$firststring = join(", ",@array);
$secondstring = join(" ",@array2);

# PRINT THE STRINGS
print "$firststring<br />";
print "$secondstring";
join.pl:
David,Larry,Roger,Ken,Michael,Tom
Pizza Steak Chicken Burgers

The characters specified in our join() argument are the characters used in between each element of the array. This allows us to format the new strings with blank spaces between each word. We could replace the blank spaces with any characters including HTML Elements such as a line break tag.

stringformatting.pl:
#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

@array2 = qw(Pizza Steak Chicken Burgers);
$string = join("<br />",@array2);

print "$string";
stringformatting.pl:

Pizza
Steak
Chicken
Burgers
PERL - Sorting Arrays

The sort() function sorts each element of an array according to ASCII Numeric standards. Please view ASCII-Table for a complete listing of every ASCII Numeric character.

Because the sort() relies on ASCII Numeric values, problems can arise with sorting capital letters and lower case letters. Let's walk through an example of exactly what can happen.

sortarrays.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

# TWO ARRAYS
@foods = qw(pizza steak chicken burgers);
@Foods = qw(Pizza Steak chicken burgers);

# SORT 'EM
@foods = sort(@foods);
@Foods = sort(@Foods);

# PRINT THE NEW ARRAYS
print "@foods<br />";
print "@Foods";
Display:
burgers chicken pizza steak
Pizza Steak burgers chicken

So what happened? We performed the same function on two nearly identical arrays and achieved complete different results. Capital letters have a lower ASCII Numeric value than lowercase letters. The fact that our second array has a mix of capitals and lowercase throws our sorting out of whack. Perhaps the best option is to first transform every element of the array into lowercase letters and then perform the sort function.

sortarrays.pl:

#!/usr/bin/perl

print "content-type: text/html \n\n"; #HTTP HEADER

@Foods = qw(Pizza Steak chicken burgers);

# TRANSFORM TO LOWERCASE
foreach $food (@Foods) {
	push(@foods,  "\L$food");
}

# SORT 
@foods = sort(@foods);

# PRINT THE NEW ARRAY
print "@foods";
Display:

burgers chicken pizza steak

This example dives off the deep end, being that we introduced a foreach loop. Don't be afraid of the loop, just understand that concept that ideally, elements need to be converted before sorting using the sort() function.



Previous                                                                                                                                                       Next

Back to Top