如果$a是一个数组数组,下面的代码可以工作,但我需要$a作为数组数组的引用.
题
我如何迭代$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;
解决方法
foreach my $row (@$array_ref) { foreach my $cell (@$row) { if ($cell eq $s) { $cell = $d; last; } } }
另外,要计算数组引用中的元素数(从上面的代码中可以看出,您不需要特定的代码),最简单的方法是:
my $count = scalar(@$array_ref); my $row_count = scalar(@{ $array_ref->[$i] }); my $last_index = $#$array_ref;
另外,要访问arrayrefs的arrayref内的数据,只需在其上使用dereference运算符:
$array_ref->[$i]->[$j]; # The second arrow is optional but I hate omitting it.
此外,您可以像创建arrayrefs一样创建arrayrefs(引用数组数组),或立即创建:
my $array_ref = [ [1,2,3],[4,5,6] ];
作为附注,请不要使用$a和$b作为标识符名称 – 它们有特殊用途(例如用于排序块)