Array Manipulation in Perl - Looping the Loop (Page 5 of 9 )
Want to obtain the size of an array? Sure - just assign the array to a scalar variable and print the value of the scalar:
#!/usr/bin/perl
# define array
@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
# obtain size of array
$count = @friends;
# print size and contents
print ("I have $count friends: @friends ");
If you're using a hash, the keys() and values() functions come in handy to get a list of all the keys and values within the array.
#!/usr/bin/perl
# define hash
%matrix = ("hero" => "neo", "villain" => "smith", "teacher" => "morpheus", "babe" => "trinity");
# returns an array of keys
@keys = keys(%matrix);
# returns an array of values
@values = values(%matrix);
Most of the time, size and key information is used in the context of a loop that iterates over the array. Here's an example of how this might work in a numerically-indexed array,
#!/usr/bin/perl
# define array
@ducks = ("Huey", "Dewey", "Louie");
# get array size
$size = @ducks;
print "And heeeeeeeeeeeeeere are the ducks: ";
# iterate over array
for ($i=0; $i<$size; $i++)
{
print "$ducks[$i] ";
}
and here's an example of iterating over an associative array using the keys() function:
#!/usr/bin/perl
# define hash
%matrix = ("hero" => "neo", "villain" => "smith", "teacher" => "morpheus", "babe" => "trinity");
print "Say hello to the characters in The Matrix: n";
# get the keys of the array with keys()
# then use the keys to get the corresponding value
# in a loop
foreach $k (keys(%matrix))
{
print $k, ": ", $matrix{$k}, "n";
}
Next: A Difficult Assignment >>
More Perl Articles
More By Harish Kamath, (c) Melonfire