Arrays in Perl

An array is a list of elements, think of it as a collection of scalars combined to one name. Though it’s primary use is being called with @, it shares with scalars and hashes the symbol $. Afterall, an array is a bunch of scalars linked together.
Array assignments/creation:

To make an array, we set it as @array = (); Like with scalars and hashes, the name following the variable sign ($ or @) can be virtually any name you like if it starts with an alpha character. An example of an array would be:

my @numbers = (1,2,3);

An array can be any length (as long as you have enough virtual memory), but it wouldn’t make much sense using one value when instead a scalar would work just fine.

To print an entire array, we would do something like this:

my @numbers = (1,2,3);
print @numbers;

How to print an array

The result of this print would be 123. Note there aren’t any spaces between keys. There are a number of ways to get around this, one of them is using quotes around the array elements and tacking a blank space at the end.

my @numbers = (“1 “, “2 “, “3 “);
print @numbers;

The result of our new print would be 1 2 3. Probably the result you’d prefer if you’re planning on storing crucial bits of information such as names and phone numbers. You can always use quotes around each of your elements, in most cases it’s required.  For confusion purposes, pretend quotes are always requried and use them around each and every single element in your list.

Now that we know how to create and print an entire array, let’s go a little deeper and take a look at some its powerful features. An easier way to do this would be to print an array inside quotes. This interprets the array as a list rather than a single line with a bunch of data.

print “@numbers”;

Using the same values as above, this would print 1 2 3. Even though this method works, it won’t work well enough to be practical in most instances. Later on you’ll see why when we discuss how to sort arrays. In this example, we are using the join function on the array @numbers and adding a blank space between each element in the list.

print join( ” “, sort @numbers);

Let’s say we don’t want to print the entire array, if we had a list of 20,000 elements and we only wanted one, why would we? You can print any element you want, afterall each of them are scalars (or more percisely can be used as scalars). Using our previous examples of “1” “2” “3”, let’s say we wanted to print out the number 2.

print $numbers[1];

Perl, like most languages, begin their numbering system at zero so of the three elements we have, the results would be [0] = 1, [1] = 2, [2] = 3. To print a single element, we must treat it as a single element and use it’s scalar sign $.

What would we do if we didn’t know how many elements our array held and wanted to print just the last one? There are two ways we can go about doing this, the simplest way being print $numbers[-1]. We will be going over the other method shortly when we get into POP.

More array assignments

You can add to an array by assigning another value. You want to be careful when doing this to be sure your number isn’t overwriting some of your data.

$numbers[3] = “4”;

Now our @numbers contains the numbers 1, 2, 3, 4. Our [3] represents the fouth digit (counting from zero as being one) and we added another number to our list. You could, for the sake of doing it, assign it so high it leaves all unused positions undefined. Not that it’s recommended as there really isn’t a logical purpose that I can imagen, it uses more bandwith and decreases the speed if the number is high enough, but for the curious you could do something like:

$numbers[999999] = “5”;

We now have 999996 undefined values because the array had to build enough room for 9999999. Again, this shouldn’t be done for real life applications, but you can have fun with it and see how it affects the speed of your scripts.
Pop and Push

POP and PUSH are methods we use to add or remove the last element of our array. If during a print out of your array and for some reason you notice the last element isn’t needed or if you want to remove it so you can work with it more specifically, you would use POP. This ‘pops’ the last element from the list.

my @numbers = (“1”, “2”, “3”);
pop(@numbers);

Now all we have left is 1 and 2, our friend 3 got pushed off and will never be seen again. If you wanted to use this, maybe you wanted to print this before discarding it.

my $lastnumber = pop(@numbers);

You can do whatever you want with “3” now, you can print it, forget about it, change it’s value and push it back in, etc. The method push is the counterpart of pop. This is how you add information to the end of everything. Sometimes we don’t want to add things to the beginning of our arrays (because they print in left to right, top to bottom, order.) Let’s say we want to add the 3 we just removed back into our list.

push(@array, “3”);

Now 1, 2 and 3 are friends again though 3 might be a little confused or mad that you got rid of him in the first place. No matter how many items you have in your array, this will put it at the end (which we could call using $numbers[-1] like we discussed earlier).
Shift and Unshift

Push and Pop work at the end of your list, similarily shift and unshift work at the beginning. Shift works like push did as this adds more data. Let’s add the number 0.

unshift(@numbers, “0”);

Our array of numbers contains the numbers 0, 1, 2 and 3 now. As you probably have guessed it already, unshift will remove the first object in your list. 0 was a trouble maker and didn’t get along with our dear friends 1, 2 or 3, so let’s do them a favor and get rid of 0 for them.

shift(@numbers);

We are now back to 1, 2 and 3 again. You can store the unshifted data into a variable if you want by assigning a scalar to it:

my $firstitem = shift(@numbers);

Reversing an array

Perl has a very nice reverse feature letting us simply reversing the printing order of the array. We are getting sick and tired of our prints coming out as “123”, so let’s reverse it.

print (reverse @numbers);

Using 1,2,3 as our array, we would get a print back of 321. As we went over before, this format isn’t very useful for every day applications. We need to be able to present the data in a useable manner, so to add spaces between elements we’ll be using split again.

print join(” “, reverse @numbers);

Counting indexes or entries

$#array returns the number of indexes or in the array. This is a useful way in dermining the last valid index in the array if you had something to push onto the end of it. We will be discussing the push functions in a later section, all you need to know right now is how to calculate the last index.

my @cookies (“chocolate chip “, “peanut butter “, “oreo”);
print $#cookies;

Many times in our scripts we would like to view just the last one or two (or few) pieces of information. You already learned how to use $index[] to assign more data into the array, so this concept shouldn’t be very new to you. If you begin index with a positive number, it starts at the beginning of the list. Using a negative index starts from the end of the list and moves backwards.

my @planets = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
print $planets[0];
print $planets[-1];

The first print will bring back “mercury” as it’s index[0]. index[-1] is the very last element in the list and in our case, it will print “marsian’s homeland”. If you wanted to view the 2nd to the last element, you would use [-2], or for the third [-3] and so on.

To better help you understand indexes, run the code from the bottom of the page called ‘indexes’..

The result of the print would be 2 because we have three items (item or index 0, 1, 2). If instead you wanted to find the number of elements in the list rather than worrying about indexes, scalar is the function we’d use. Scalar takes any expression and returns the scalar value. Since we are using it on a list @cookies, it returns the number of array entries you have.

my @planets = (“mercury”, “mars”, “earth”, “saturn”, “pluto”, “marsian’s homeland”);
print $planets[0];
print $planets[-1];

scalar @cookies;
Merging

Your company just merged with another firm down the street and you want one large list of employees rather than two separate lists. This can be a fairly common task and in Perl it’s quite simple to merge two or more arrays to combine one, larger array.

my @employees1 = (“Fred Flintstone”, “Barny Rubble”, “Dino Fintstone”);
my @employees2 = (“Wilma Flintson”, “Bamm-Bamm”, “Jigglypuff”);
my @allemployees = (@employees1, @employees2);

@allemployees now contains all the names from employees1 and employees2 with employees1’s data first. If you want the second sent of employees to appear on top, all you have to do is change the assignment order to = (@employees2, @employees1);


Array splicing

Perl enables us to be able to remove (and optionally return) more than one element at a time. We can do this using array splices. A splice takes a list, an offset and a lenth.

splice (@array, offset, length);

The offset is an integer where you want the splicing to begin. You use array indexing again (isn’t it remarkable how often these indexes come up?). The length is also a whole number and this is how many indexes you want to splice.

my @colors = (“red”, “blue”, “orange”, “purple”, “pink”, “white”); splice(@colors, 0, 2);
print @colors;

We set the offset at 0, which is the 0 index red and the length of 2 . This will remove the first three sets of information from the list leaving purple, pink and white left. If we spliced (@colors, 2, 1), we would be removing the index[2] (orange). Since our length is only 1, we’re only removing one index.


Sorting

Printing a list of 100,000 names would be a mess if we couldn’t sort the list, wouldn’t it? You’d have names or phone numbers or dates in insertion order rather than a user-friendly alphabetical or numerical order. Luckily for us, Perl makes it simple for us to sort an entire list alphabetically.

my @animals = (“frog”, “toad”, “snake”, “grasshopper”, “bird”);
print join(” “, sort @animals);

sort (@array) will take the array and put it in alpha-numerical order for you. Using sort(@array) on our animals, we would get back : bird, frog, grasshopper, snake, toad. If we had numbers (“1”, “3”, “5”) in with our animals, the numbers would print before the animals.
Deleting

Sometimes you will want to remove a certain element from your list. This can be done using delete. To remove a single piece of information we need to treat the list as a scalar.

my @animals = (“frog”, “toad”, “snake”);
delete $animals[0];

Oh oh, it appears our newest pet frog was eaten by a snake in our garden. It’s a very sad tragedy and we will mourn deeply for the rest of our lives, but to remove our dead frog’s memory we use the delete $array[index] command..

If instead you wanted to delete an entire array, the quickest way would be to assign it a null value. A null value is different than an undefined value, so don’t try @animals = undef; thinking it’ll delete your array. Instead, use:

@animals = ();

The toad and the snake ran away, that’s three animals we just lost. How ever are we going to live with ourselves? Between the tears you cry, we assign our list of animals to a blank list and we have nothing else to live for 🙁 .


Summary

Arrays can be a very useful way for you to reuse information from a list. You have learned how to create an array, read information from an entire set of values and how to pick apart just pieces of information. You have also learned how to merge more than one list together to form a single and larger list. Using the techniques we went over, you should now be able to determine how many indexes you have and know how to delete and/or store certain indexes into a new array all by itself.

Author: Syperder Co
I waltzed into the Web Design community as a professional when I was just 15 years of age founding SpyderWebDesigns. Through the years my interests shifted from web development to backbone and user interaction.In 2000 Sulfericacid.com was born. The world’s largest free and 100% ad-free web site where you could use and download 24 Perl and CGI script along with tutorials without limits or restrictions. January 2005 the site was renamed to SpyderScripts.com as a subsidy of SpyderCo.

In 2001 I also founded an SEO company SpyderSubmission.com. We’ve helped nearly 2300 web sites achieve higher rankings than they ever could have imagined since our launch four years ago.

On a more personal note, I’ve attained 28 certifications from BrainBench.com and about 40 certifications in total from all resources. One of these is a near Masters in Perl which ranks second highest test score in the state and 17th throughout the country.

I have a Perl Abbot status on PerlMonks.org working on getting my Perl Saint status this fall.