Reputation: 3496
I have the below code and I'm attempting to print out only the first row of 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.
Upvotes: 1
Views: 5440
Reputation: 385565
$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";
}
Upvotes: 5
Reputation: 67900
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);
Upvotes: 4
Reputation: 46965
Try this:
for (my $c = 0; $c <= (scalar @{$list[0]}); $c++)
for the loop condition
Upvotes: -1