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.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;
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.Quarter
Dime
Nickel
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
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 />";
Display:
Quarter Dime Nickel
QuarterDimeNickel
QuarterDimeNickel
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.26
20
26
There are 20 numerical elements
There are 26 letters in the alphabet!
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.
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!
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:
Function | Definition |
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 |
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 />";
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
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";
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.Larry David Roger Ken Michael Tom
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 "$astring<br />"; print "$string";
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.Pizza Steak Chicken Burgers
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
Steak
Chicken
Burgers
PERL - Sorting Arrays
The sort() function sorts each element of an array according to ASCII Numeric standards.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.Pizza Steak burgers chicken
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.
0 comments:
Post a Comment