Question

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
Was it helpful?

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: $!";

OTHER TIPS

Along with Toolic's addition I had to make some edits due to the specific type of data I was dealing with. This was an extremely large set with engineering symbols & units and negative numbers with long decimals. For reference, my final code is below.

use strict;
use warnings;
use Text::CSV;
use Data::Dump qw(dump);
use Array::Transpose;
my @data;   # 2D array for CSV data
my $file = 'rawdata.csv';

my $csv = Text::CSV->new({ binary => 1, quote_null => 0 });
open my $fh, '<', $file or die "Could not open $file: $!";

while( my $row = $csv->getline( $fh ) ) { 
#shift @$row;        # throw away first value, I needed the first values.
push @data, $row;
}

@data=transpose(\@data);

open $fh, ">:encoding(utf8)", "rawdata_trans.csv" or die "rawdata_trans.csv: $!";
for (@data) {
$csv->print($fh, $_);
print $fh "\n";
}
close $fh or die "rawdata_trans.csv: $!";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top