我有下面的代码,我试图只打印出这个2d数组的第一行
# how many columns
for (my $c = 0; $c <= $#list[0]; $c++) {
print $list[0][$c]."\n";
数据应该是
[0] => "ID,Cluster,Version"
[1] => "2,32,v44"
错误:
syntax error at ./connect_qb.pl line 107, near "$#list["
syntax error at ./connect_qb.pl line 107, near "++) "
Execution of ./connect_qb.pl aborted due to compilation errors.
答案 0 :(得分:5)
$list[0]
是对数组的引用,因此数组是
@{ $list[0] }
所以该数组的最后一个元素是
$#{ $list[0] }
所以你要用
for my $c (0 .. $#{ $list[0] }) {
print "$list[0][$c]\n";
}
或
for (@{ $list[0] }) {
print "$_\n";
}
答案 1 :(得分:4)
你应该避免使用c-style for循环。这是一种方法。
use strict;
use warnings;
use feature qw(say);
my @a = (["ID","Cluster","Version"], ["2","32","v44"]);
say for (@{$a[0]});
稍微不那么令人困惑的解除引用:
...
my $ref = $a[0];
say for (@$ref);
答案 2 :(得分:0)
这是一个简单的衬垫
print join(",",@{$list[0]}),"\n";
答案 3 :(得分:-1)
试试这个:
for (my $c = 0; $c <= (scalar @{$list[0]}); $c++)
表示循环条件