2

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.

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
2
  • 1
    You don't need to use both Text::CSV and Text::CSV_XS. If you have Text::CSV_XS installed, use Text::CSV; will actually use Text::CSV_XS automatically. Commented Mar 18, 2014 at 18:34
  • True, I should have removed that it got copied over from earlier attempts. Commented Mar 18, 2014 at 18:35

2 Answers 2

2

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: $!";
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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.