Array Manipulation in Perl - Harnessing Elements (Page 4 of 9 )
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");
This works with associative arrays too:
#!/usr/bin/perl
# define hash
%dinner = ("starter" => "fried squid rings", "main" => "roast chicken", "dessert" => "chocolate cake");
# change element
$dinner{"dessert"} = "tiramisu";
# hash now looks like this
%dinner = ("starter" => "fried squid rings", "main" => "roast chicken", "dessert" => "tiramisu");
You can print the contents of an array simply by using the array in a print() function call, as below:
#!/usr/bin/perl
# define array
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
# print contents
print "@friends ";
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);
# get array values
for ($x=0; $x<$size; $x++)
{
print ("Enter item ", ($x+1), ": ");
$val = ;
chomp ($val);
$data[$x] = $val;
}
# 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.
Next: Looping the Loop >>
More Perl Articles
More By Harish Kamath, (c) Melonfire