Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over an Array of Arrays as reference?

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;
like image 726
Sandra Schlichting Avatar asked Aug 17 '12 15:08

Sandra Schlichting


2 Answers

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)

like image 88
DVK Avatar answered Sep 23 '22 03:09

DVK


To dereference in Perl, you have a variety of options. For starters, I suggest you read perlref. Here is the relevant code portion with a minimum of changes, so you can see what needs to be different (however, I agree with others' suggestions to make your code more Perlish).

for my $i ( 0 .. $#$a ) {
    for my $j ( 0 .. $#{ $a->[$i] } ) {
        if ($a->[$i][$j] eq $s) {
            $a->[$i][$j] = $d;
            last;
        }
    }
}
like image 26
dan1111 Avatar answered Sep 24 '22 03:09

dan1111