Array Manipulation in Perl - Back to Basics (Page 2 of 9 )
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:
#!/usr/bin/perl
# define array
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
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:
#!/usr/bin/perl
# define array
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
# prints "Phoebe"
print $friends[2];
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
#!/usr/bin/perl
# define array
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
is equivalent to these:
#!/usr/bin/perl
# define array
$friends[0] = "Rachel";
$friends[1] = "Monica";
$friends[2] = "Phoebe";
$friends[3] = "Chandler";
$friends[4] = "Joey";
$friends[5] = "Ross";
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.
Next: Hash Bang >>
More Perl Articles
More By Harish Kamath, (c) Melonfire