References and Data Structures

Reading the two-dimensional array data from a file

Let's now create the two-dimensional array by reading data from a file. Our source file is names.txt.

Here is one way to create @data:

#!/usr/bin/perl

open (SOURCE, names.txt) || die "cannot open names.txt": $!";

while (<SOURCE>) {
   chomp ($_);
   @names = split (/:/, $_);
   push (@data, [@names]);
}
Look at the line push (@data, [@names]);. We added the names as a reference to an anonymous list of names. The list contains all the elements of @names. This way @names is "forgotten" by the program the moment it gets out of scope, namely in the next iteration of the loop.


Table of Contents.
Previous | Next.