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.
To modify a particular element of an array, use the index/key notation to accomplish your task, like this:
#!/usr/bin/perl # define array @friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross"); # now change one of its elements $friends[3] = "Janice"; # array now looks like this @friends = ("Rachel", "Monica", "Phoebe", "Janice", "Joey", "Ross");
The fact that array values can be accessed and manipulated using a numeric index makes them particularly well-suited for use in a loop. Consider the following example, which asks the user for a set of values (the user can define the size of the set), stores these values in an array, and then prints them back out.
#!/usr/bin/perl # get array size print ("How many items? "); $size = ; chomp ($size);
# iterate over array # print array values print ("Here is what you entered: n"); for ($x=0; $x<$size; $x++) { print ("Element $x: $data[$x]n"); }
Here's what the output looks like:
How many items? 3 Enter item 1: red Enter item 2: orange Enter item 3: green Here is what you entered: Element 0: red Element 1: orange Element 2: green
The first thing I've done here is ask the user for the number of items to be entered - this will tell me the size of the array. Once that information has been obtained, it's pretty easy to set up a "for" loop to obtain that number of values through user input at the command prompt. Every time the user enters one of these values, a counter variable is incremented, this counter variable corresponds to the index in the @data array that is being constructed as the loop executes. Once all the values have been entered, another "for" loop is used to iterate over the newly-minted @data array, and print the values stored in it.
The second loop runs as many times as there are elements in the array. In this specific example, I know the size of the array because I had the user enter it at the beginning of the script, but you can also obtain the array size programmatically, as you'll see on the next page.