References and Data Structures

Accessing data in the two-dimensional array

Accessing individual elements

To access individual elements of the two-dimensional array, we use the arrow operator.

Let's store the value 'Denmark' in a variable of its own.

To access 'Denmark' from @data we write:

$some_country = $data[2]->[3];
$data[2] is written without an arrow, because @data is a real array. But after [2] we need an arrow, because the element of index 2 in @data (countries) is itself a reference to an array (the list of countries).

Perl will also accept this:

$some_country = $data[2][3];

Printing all elements

Printing all elements of a data structure can be done in several ways, depending on how compact you like your code to be. Remember, though, that compactness is usually at the expense of clarity.

To print all elements of @data in tab-delimited format we write:

foreach $type (@data) {
   foreach $elem (@{$type}) {
      print "$elem\t";
   }
   print "\n";
}

Table of Contents.
Previous | Next.