Print a line of a two-dimensional array in Perl

Asked

Viewed 63 times

0

I have an array @data, two-dimensional, and I want to record line after line in a file. I’m doing so, for each line $i:

print (ECR $data[$i][0]);
for $j (1 .. $lastcol) {
  print (ECR "," . $data[$i][$j]);
}
print (ECR "\n");

But I’d like to do something like:

print (ECR join (",", $data[$i][0 .. lastcol])) . "\n";

How to do?

  • Why do you want to do so ? already tried ? even if it works, I think it won’t be worth it, will duplicate the content of the two-dimensional matrix in memory...there would have to be a specific reason to do it this way you want it to

1 answer

1

A one-line code solution using the function map:

print ECR map { (join (",", @{$_}))."\n" } @data;

Another solution, simpler, with few lines of code using references:

for my $linha (@data) {
    print ECR join (",", @{$linha}), "\n";
}

A more similar solution to what you proposed, using an indexer and references:

for (my $i = 0; $i < @data; $i++) {
    print (ECR join (",", @{$data[$i]}) . "\n");
}

Finally, if it is really necessary to do the column answer:

my $num_linha = @data;
my $num_coluna = @{$data[0]};

for (my $i = 0; $i < $num_linha; $i++) {
        print ECR join (",", $data[$i]->@[0..$num_coluna-1])."\n";
}

If you want to do things more advanced and faster in CSV format, use the Text::CSV or Text::CSV_XS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.