How to loop over an Array of Arrays as reference?
arrays, perl, reference
Solution
foreach my $row (@$array_ref) {
foreach my $cell (@$row) {
if ($cell eq $s) {
$cell = $d;
last;
}
}
}
Also, to compute the # of elements in array reference (which as you can see from above code you don't need for your specific code), the easiest approach is:
my $count = scalar(@$array_ref);
my $row_count = scalar(@{ $array_ref->[$i] });
my $last_index = $#$array_ref;
Also, to access the data inside an arrayref of arrayrefs, you simply use the dereference operator on it:
$array_ref->[$i]->[$j]; # The second arrow is optional but I hate omitting it.
In addition, you can create your arrayref of arrayrefs the way you did (take a reference to array of arrays), or right away as a reference:
my $array_ref = [
[1,2,3]
,[4,5,6]
];
As a side note, please never use `$a` and `$b` as identifyer names - they have special purpose (used in sort blocks for example)
Problem
The below code works if `$a` is an Array of Arrays, but I need `$a` to be an reference to the Array of Arrays. Question How do I iterate through `$a`? ``` #!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @AoA = ( ['aaa','hdr','500'], ['bbb','jid','424'], ['ccc','rde','402'], ); my $a = \@AoA; my $s = "bbb"; my $d = "ddd"; for my $i ( 0 .. $#a ) { for my $j ( 0 .. $#{ $a[$i] } ) { if ($a[$i][$j] eq $s) { $a[$i][$j] = $d; last; } } } print Dumper $a; ```