Getting Several Values from a Hash
-
Separate the keys by commas in the curly braces.
-
Since we are dealing with multiple data, use the @ for arrays, not the
$ for scalars.
-
@ages = @studentData{'Ben', 'Sarah', 'Phil'};
-
Will give you an array called @ages with three values: 25, 36, and 40.
-
A shortcut for getting all of the values: use the values function.
-
@ages = values(%studentData);
-
Gives you an array, @ages, containing all of the values (ages) in the hash
%studentData.
-
Now, combine this with the foreach loop we covered earlier:
foreach $age (@ages) {
print "<br>Age: $age";
}
-
Remember, foreach is a loop made for arrays. It iterates through
each array element in the array in parenthesis, assigns that element to
the scalar between the foreach and the array, and then allows you to use
that value between the curly braces. Each time the loop executes
(once for each element), Perl assigns the corresponding element, one at
a time, to the scalar $ages. Thus, the code above will print <br>Age:
the age value once for each age in the @ages array. Wow, that's
a mouthfull.
There's an easy way to get keys, too.
Home