arrays - 如何循环遍历数组作为引用?

标签 arrays perl reference

如果 $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; 

此外,要访问 arrayref 的 arrayref 中的数据,您只需在其上使用取消引用运算符:
$array_ref->[$i]->[$j]; # The second arrow is optional but I hate omitting it.

此外,您可以按照您的方式创建 arrayrefs 的 arrayref(引用数组数组),或者立即作为引用:
my $array_ref = [
         [1,2,3]
         ,[4,5,6]
        ];

作为旁注,请不要使用 $a$b作为标识符名称 - 它们有特殊用途(例如用于排序块)

关于arrays - 如何循环遍历数组作为引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12008455/

相关文章:

C++:创建迭代器嵌套类的实例

assemblies - 在同一文件夹中使用同一程序集的不同版本

c++ - 在 C++ 中的递归函数中使用引用参数

c++ - 在不创建新 int[size] 的情况下声明数组时出现 SIGSEGV 错误

javascript - 更改数组内对象的大小写标题

perl - 在 perl 中使用 Redis.pm 管道

linux - 在 Linux Redhat 中的 Eclipse Classic 中运行 Perl 脚本

c - 在C编程中达到EOF时如何退出stdin

arrays - 如何过滤数组的数组?

perl - 逐位读取二进制文件