开发者

print first row of a 2d Array in Perl

开发者 https://www.devze.com 2023-03-29 08:11 出处:网络
I have the below code and I\'m attempting to print out only the first row of开发者_如何学Python this 2d array

I have the below code and I'm attempting to print out only the first row of开发者_如何学Python this 2d array

# how many columns
for (my $c = 0; $c <= $#list[0]; $c++) {
print $list[0][$c]."\n";

the data should be something like

[0] => "ID,Cluster,Version"
[1] => "2,32,v44"

The Error:

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]

is a reference to an array, so the array is

@{ $list[0] }

so the last element of that array is

$#{ $list[0] }

so you'd use

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

or

for (@{ $list[0] }) {
   print "$_\n";
}


You should avoid c-style for loops. Here's one way to do it.

use strict;
use warnings;
use feature qw(say);

my @a = (["ID","Cluster","Version"], ["2","32","v44"]);
say for (@{$a[0]});

A slightly less confusing dereferencing:

...
my $ref = $a[0];
say for (@$ref);


Here is a simple one liner for that

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


Try this:

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

for the loop condition

0

精彩评论

暂无评论...
验证码 换一张
取 消