References and Data Structures

Additional examples of dereferencing

When you want to manipulate data that is referred to by a reference, you can first dereference the data and store the result in another variable. That's what we did in the previous example when we wrote, inside the print_html subroutine:
@synonyms_list = @{$ref_to_synonyms};
%info_hash     = %{$ref_to_information};
However, we can also use the dereferencing mechanism to work with the referent data directly. This way, we won't have to define @synonyms_list and %info_hash, but instead we work directly with $ref_to_synonyms and $ref_to_information.

Examples

1. Let's say we are inside the print_html subroutine, but we want to work with $ref_to_synonyms, without dereferencing it on the top of the subroutine. To print all elements of the array that is pointed to by this reference, in HTML format, we write:
foreach $synonym (@{$ref_to_synonyms}) {
   print HTML "<LI>$synonym\n";
}

2. Similarly, let's say we want to loop over all elements of a hash by using the reference that points to that hash, we write:

foreach $property (sort keys %{$ref_to_information}) {
   print HTML "<TR>",
              "<TD>$property</TD>",
              "<TD>${$ref_to_information}{$property}</TD>",  
              "</TR>\n";
}


Table of Contents.
Previous | Next.