in reply to Reading arrays
This might seem a bit confusing since it is using a multi-dimensional array, but it's not really a big deal. The @{} part is used to specify that you want to deal with the entire column array, and not a specific element. A specific element is referenced as $data[$x][$y], such as $data[0][0] which is the first element of the first column.use strict; # Warns about mistakes (important) my @data; # Data storage variable my $filename = "data.dat"; # Filename constant # Open a handle to the specified file, or die with a # warning that it could not be done. open (DAT, $filename) || die "Could not open $filename\n"; # Now read through the contents of the file while (<DAT>) { chomp; # Removes trailing linefeed from input if ($_ eq "block") { # Put "block" into the two columns push (@{$data[0]}, $_); push (@{$data[1]}, $_); } elsif (/^\s*(\d+),(\d+)/) # Look for " nn,nn" { # The first group of digits, expressed as "\d+", # is 'memorized' as $1, with the second group as # $2 (and so on). \s* means "0 or more spaces" # and is not memorized (ignored) push (@{$data[0]}, $1); push (@{$data[1]}, $2); } else { # $. is the current input line (perldoc perlvar) print "Invalid input line $.\n"; } } close (DAT);
The data structure is a little complicated because you want to have each column in a separate array. If instead you put each row into the array, it would be much simpler.for (my $i = 0; $i < @{$data[0]}; $i++) { print "$data[0][$i],$data[1][$i]\n"; }
|
|---|