arraysperlcsvtranspose

Create CSV file from 2d array perl


I am trying to load a csv file, transpose it and write a new one. I have everything working correctly except writing a new file. I have looked around online without success.

use strict;
use warnings;
use Text::CSV;
use Data::Dump qw(dump);
use Array::Transpose;

my @data;   # 2D array for CSV data
my $file = 'sample_array.csv';

my $csv = Text::CSV->new;
open my $fh, '<', $file or die "Could not open $file: $!";

while( my $row = $csv->getline( $fh ) ) { 
shift @$row;        # throw away first value
push @data, $row;
}
@data=transpose(\@data);
dump(@data);

The output here is the transposed array @data (["blah", 23, 22, 43], ["tk1", 1, 11, 15],["huh", 5, 55, 55]). I need that output to be written to a new CSV file.

CSV file:

text,blah,tkl,huh
14,23,1,5
12,22,11,55
23,42,15,55

Solution

  • Refer to the code after dump. This was derived from the Text::CSV SYNOPSIS:

    use strict;
    use warnings;
    use Text::CSV;
    use Data::Dump qw(dump);
    use Array::Transpose;
    
    my @data;   # 2D array for CSV data
    my $file = 'sample_array.csv';
    
    my $csv = Text::CSV->new;
    open my $fh, '<', $file or die "Could not open $file: $!";
    
    while( my $row = $csv->getline( $fh ) ) { 
        shift @$row;        # throw away first value
        push @data, $row;
    }
    @data=transpose(\@data);
    dump(@data);
    
    open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
    for (@data) {
        $csv->print($fh, $_);
        print $fh "\n";
    }
    close $fh or die "new.csv: $!";