0

How can I output a 2 dimensional array to a csv file in perl?

For example I have constructed a dimensional array as:

for my $i(0..100) {
    for my $j (0..50) {
        $data[$i][$j]=0;
    } 
}

And I want to output it to a csv file for future reference. And this csv file should be read and reconstructed to the 2 dimensional array. using code like:

my $outfilename="output.csv"; 
my $csv = Text::CSV->new;
open OUT , '<', $outfilename or die "Could not open $outfilename: $!";

while( my $row = $csv->getline( OUT ) ) { 
    push @output, $row;
}
close OUT;

What is an efficient way to do this?

1
  • 1
    What is preventing you from doing for my $row (@data) { $csv->print(*OUT, $row); } to print the csv file? If that is how you intend to read it, it would make sense that it be the way you write it as well. Commented Mar 27, 2013 at 5:12

1 Answer 1

3

As usual, CPAN is your friend: you can use Tie::Array::CSV

THe example in the documentation looks pretty much like what you need:

use strict; use warnings;
use Tie::Array::CSV;
tie my @file, 'Tie::Array::CSV', 'filename';

# print $file[0][2];
$file[3][5] = "Camel";

As for efficiency, it looks very efficient with regard to your time. The module has a caveat that says "certain actions may be very inefficient [...] (for) example, (un)shift-ing". It doesn't look like your case would be impacted though.

Sign up to request clarification or add additional context in comments.

2 Comments

I am sorry, but it is not what I want. The tie function actually extract the content from a csv file and put it into a two dimensional array. What I want is to print a two dimensional array to a csv file. Do you know how to do that?
Actually the module does that too. I've commented out the "print..." line: if you run the code you'll find a file called "filename" in the directory you ran the script in. It will contain three empty lines and one containing ",,,,,Camel". The rows are the fits dimension of the array, and columns the second.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.