用Perl打印2d数组的第一行



我有下面的代码,我试图只打印出这个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.
$list[0]

是对数组的引用,因此该数组是

@{ $list[0] }

所以这个数组的最后一个元素是

$#{ $list[0] }

所以你应该使用

for my $c (0 .. $#{ $list[0] }) {
   print "$list[0][$c]n";
}

for (@{ $list[0] }) {
   print "$_n";
}

循环应该避免使用c样式。这里有一种方法。

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);

这里有一个简单的单行

print join(",",@{$list[0]}),"n";

试试这个:

for (my $c = 0; $c <=  (scalar @{$list[0]}); $c++) 

对于循环条件

相关内容

  • 没有找到相关文章

最新更新