Skip to content

Instantly share code, notes, and snippets.

@berteh
Created July 23, 2013 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berteh/6060700 to your computer and use it in GitHub Desktop.
Save berteh/6060700 to your computer and use it in GitHub Desktop.
Transpose a CSV array
#! /usr/bin/perl
# transposes input.csv to output.csv.
#
# eg: input.csv:
# "id","1","2"
# "A1","a","b"
#
# output.csv will be
# "id","A1"
# "1","a"
# "2","b"
#
### do not edit below this line ###
use strict;
my $infile = 'input.csv';
my $outfile = 'output.csv';
open (F, $infile) || die ("Could not open $infile!");
my @data = ();
my ($line, $i, $j,$check);
while ($line = <F>) {
push(@data,[split("\",\"", $line)]);
}
print "got ".scalar(@data)." lines from $infile, with ".scalar($#{$data[0]})." items in first line\n";
close (F);
(scalar(@data)>0) || die ("$infile is empty");
# quick check to verify no splitting was done in actual data, i.e. all lines have same numbers of data
# and remove starting and trailing " from each line
$check = 0;
for $i ( 0 .. $#data ) {
$check = $check + scalar($#{$data[$i]});
$data[$i][0] = substr($data[$i][0],1);
chop($data[$i][scalar($#{$data[$i]})-1]);
}
$check = $check / scalar(@data);
print "average line length: $check\n";
($check == scalar($#{$data[0]})) || die ("please correct input.csv to ensure the following characters do not appear in the data: ".'","'."\n");
open(OUT, "> $outfile") || die "$outfile cannot be opened.";
for $j ( 0 .. $#{$data[0]} ) {
for $i ( 0 .. $#data ) {
print OUT "\"$data[$i][$j]\"";
if ($i<($#data)) {print OUT ",";}
}
print OUT "\n";
}
close (OUT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment