References and Data Structures

Looping over elements of array and hash references

To practice dereferencing, let's demonstrate looping over an array and over a hash, once using array/hash variables, and once using their references.

We use the same PLD1-related variables as in the previous slides.

Looping over an array


Using an array variable (@synonyms) Using an array reference ($ref_to_synonyms)
Disregard indexes
foreach $name (@synonyms) {
   print "$name\n";
}
foreach $name (@{$ref_to_synonyms}) {
   print "$name\n";
}
Keep indexes
my $last_index = $#synonyms;
foreach $i (0 .. $last_index) {
   print "$i. $synonyms[$i]\n";
}
my $last_index = $#{$ref_to_synonyms};
foreach $i (0 .. $last_index) {
   print "$i. $ref_to_synonyms->[$i]\n";
}

Looping over a hash


Using a hash variable (%information) Using a hash reference ($ref_to_information)
Sorted keys
foreach $key (sort keys %information) {
   print "$key: $information{$key}\n";
}
foreach $key (sort keys %{$ref_to_information}) {
   print "$key: $ref_to_information->{$key}\n";
}
Unsorted keys
while (($key, $value) = each (%information)) {
   print "$key: $value\n";
}
while (($key, $value) = each (%{$ref_to_information})) {
   print "$key: $value\n";
}


Table of Contents.
Previous | Next.