I’m trying to iterate over a 2D array that is structured in this specific way. Whether or not this is a good way to structure the array is another question – I still need to be able to iterate over it (if it is possible).
@row1 = ( "Current Scan", "Last Month");
@row2 = ( "240", "0");
@row3 = ( "226", "209");
@row4 = ( "215", "207");
@array = (\@row1, \@row2, \@row3, \@row4);
print Dumper(@array);
printarray(@array);
Dumper gives me the following output:
$VAR1 = [
'Current Scan',
'Last Month'
];
$VAR2 = [
'240',
'0'
];
$VAR3 = [
'226',
'209'
];
$VAR4 = [
'215',
'207'
];
I’ve tried several for loops with no success. Each only prints the first row ($VAR1) and quits. Here is my most recent attempt:
sub printarray {
@array = shift;
$rowi = 0;
foreach my $row (@array) {
for (my $coli = 0; $coli <= @$row; $coli++) {
print "$array[$rowi][$coli]\n";
}
$rowi++;
}
}
I’m obviously overlooking something simple. What am I doing wrong? Thanks in advance!
If you want just print the array, try following code:
If you need indexes for some purpose, here we go:
The idea is that
@arrayin scalar context returns number of elements in array. And@{ $array[$row_i] }is a little more tricky. It dereference array stored in$array[$row_i].Update for subroutine:
In perl you can pass array by reference:
You can also pass a copy of array:
For more details take a look at How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? manual page.
And please add
use strict;at the begining of programm. It’ll force you to declare all variables, but will save bunch of time if you type something incorrectly.