Array Manipulation in Perl - A Difficult Assignment (Page 6 of 9 )
You can assign the elements of an array to scalar variables, as in the following example:
#!/usr/bin/perl
# define array
@human = ("John", "Doe");
# assign array contents to variables
($fname, $lname) = @human;
# print variables
print ("My name is $fname $lname");
This won't work with an associative array, though - for that, you need the each() function. Every time each() runs on a hash, it creates an array containing two elements: the hash key and the corresponding hash value.
#!/usr/bin/perl
# define hash
%matrix = ("hero" => "neo", "villain" => "smith", "teacher" => "morpheus", "babe" => "trinity");
# get first pair
($character, $name) = each (%matrix);
print "$character = $namen";
# get second pair
($character, $name) = each (%matrix);
print "$character = $namen";
# and so on...
The each() function comes in particularly handy when you need to iterate through an associative array, as it is well-suited for use in a "while" loop:
#!/usr/bin/perl
# define hash
%matrix = ("hero" => "neo", "villain" => "smith", "teacher" => "morpheus", "babe" => "trinity");
# iterate through hash with each
# returns villain = smith hero = neo babe = trinity teacher = morpheus
while (($character, $name) = each (%matrix))
{
print "$character = $namen";
}
You can assign the array itself to another variable, thereby creating a copy of it, as below:
#!/usr/bin/perl
# define array
@john = ("John", "Doe");
# copy array
@clone = @john;
# print copy
print ("I am a clone named @clone");