Growing Your Own
Those big list assignments are well and good for creating a fixed data structure, but what if you want to calculate each element on the fly, or otherwise build the structure piecemeal?
Let’s read in a data structure from a file. We’ll assume that it’s a plain text file, where each line is a row of the structure, and each line consists of elements delimited by whitespace. Here’s how to proceed:[131]
while (<>) {
@tmp = split; # Split elements into an array.
push @AoA, [ @tmp ]; # Add an anonymous array reference to @AoA.
}Of course, you don’t need to name the temporary array, so you could also say:
while (<>) {
push @AoA, [ split ];
}If you want a reference to an array of arrays, you can do this:
while (<>) {
push @$ref_to_AoA, [ split ];
}Both of those examples add new rows to the array of arrays. What about adding new columns? If you’re just dealing with two-dimensional arrays, it’s often easiest to use simple assignment:[132]
for $x (0 .. 9) { # For each row...
for $y (0 .. 9) { # For each column...
$AoA[$x][$y] = func($x, $y); # ...set that cell
}
}
for $x ( 0..9 ) { # For each row...
$ref_to_AoA–>[$x][3] = func2($x); # ...set the fourth column
}It doesn’t matter in what order you assign the elements, nor
does it matter whether the subscripted elements of @AoA are already there or not; Perl will
gladly create them for you, setting intervening elements to the
undefined value as need be. Perl will even create the original
reference in $ref_to_AoA for you if it needs ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access