如何在 Perl 中创建多维数组? [英] How can I create multidimensional arrays in Perl?

查看:46
本文介绍了如何在 Perl 中创建多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Perl 有点陌生,但这是我想要做的:

I am a bit new to Perl, but here is what I want to do:

my @array2d;
while(<FILE>){
  push(@array2d[$i], $_);
}

它无法编译,因为 @array2d[$i] 不是数组而是标量值.

It doesn't compile since @array2d[$i] is not an array but a scalar value.

我应该如何将@array2d 声明为数组的数组?

How should I declare @array2d as an array of array?

当然,我不知道我有多少行.

Of course, I have no idea of how many rows I have.

推荐答案

要创建数组数组,或者更准确地说是数组引用数组,请尝试以下操作:

To make an array of arrays, or more accurately an array of arrayrefs, try something like this:

my @array = ();
foreach my $i ( 0 .. 10 ) {
  foreach my $j ( 0 .. 10 ) {
    push @{ $array[$i] }, $j;
  }
}

它为您将值推送到取消引用的 arrayref 上.您应该能够访问这样的条目:

It pushes the value onto a dereferenced arrayref for you. You should be able to access an entry like this:

print $array[3][2];

这篇关于如何在 Perl 中创建多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆