Over the course of this tutorial, I'll be examining Perl's arrays in detail, explaining what they are, how they work, and how you can use them to get things done faster, better and cheaper. In addition to providing a gentle introduction to Perl arrays and hashes in general, this article will also offer you a broad overview of Perl's array manipulation functions, providing you with a handy reference that should help you write more efficient code.
I'll begin right at the top, with the answer to a basic question: what's an array, anyhow?
In all programming languages, an array is a data structure that lets you store multiple values in a single variable. This structure is a very useful method of storing and representing related information. In Perl, array variables look like any other variable, with the exception that array variable names are always preceded by an @ symbol. Here's an example:
Thus the array variable @friends contains six elements, the names of the "Friends" crew.
The various elements of the array are accessed via an index number, with the first element starting at zero (this is sometimes referred to as "zero-based indexing"). So, to extract the first element of the array above, you'd use the notation $friends[0], while the notation $friends[5] would give you the sixth element of the array, "Ross". Here's a simple code snippet explaining this:
In case you don't want to define the array all at once, you can define it incrementally, by assigning values to the array one at a time using the index notation above. For example, this line of code
Notice that you don't have to do anything special to bring an array variable into existence, like declare it with a keyword or instantiate an object to hold its values - Perl identifies the notation being used and creates the data structure appropriately.