2 # transpose_table transposes tables, and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2011 by Don Armstrong <don@donarmstrong.com>.
6 # $Id: perl_script 1825 2011-01-02 01:53:43Z don $
17 transpose_table - Transposes a table
24 --tsv, -t tab separated value mode (Default)
25 --ssv, -s space separated value mode
26 --csv, -c comma separated value mode
27 --bigfile,-b Big file; use disk
28 --debug, -d debugging level (Default 0)
29 --help, -h display this help
30 --man, -m display manual
38 Debug verbosity. (Default 0)
42 Display brief usage information.
60 use File::Temp qw(tempdir);
62 use MLDBM qw(DB_File Storable);
65 use List::Util qw(max);
67 my %options = (debug => 0,
78 'debug|d+','help|h|?','man|m');
80 pod2usage() if $options{help};
81 pod2usage({verbose=>2}) if $options{man};
83 $DEBUG = $options{debug};
86 if (0 == grep {exists $options{$_}} qw(tsv ssv csv)) {
89 if (1 < grep {exists $options{$_}} qw(tsv ssv csv)) {
90 push @USAGE_ERRORS,"You can only pass one of --tsv, --ssv, or --csv";
94 # we'll use this as a special indicator to read stdin
98 push @USAGE_ERRORS,"Exactly one file must be specified";
101 pod2usage(join("\n",@USAGE_ERRORS)) if @USAGE_ERRORS;
107 elsif ($options{ssv}) {
111 my $csv = Text::CSV->new({sep_char=>$sep_char});
116 if ($options{bigfile}) {
117 my $temp_dir = tempdir(CLEANUP=>1);
118 tie %rows,"MLDBM","$temp_dir/bigfile", O_CREAT|O_RDWR, 0600 or
119 die "Unable to tie '$temp_dir/bigfile': $!";
123 for my $file (@ARGV) {
125 if (not defined $file) {
130 $fh = IO::File->new($file,'r') or
131 die "Unable to open $file for reading: $!";
136 die "Unable to parse line $. of $file" unless $csv->parse($_);
137 my @row = $csv->fields();
138 $cols = max(scalar @row,$cols);
139 for my $i (0..$#row) {
140 $rows{$rows.'-'.$i} = $row[$i];
143 print STDERR "\rInput $rows rows";# if not ($rows-1) % 50;
147 for my $i (0..($cols-1)) {
149 for my $j (0..($rows-1)) {
150 push @row,$rows{$j.'-'.$i};
152 $csv->print($fh,\@row);
154 print STDERR "\rOutput ".($i+1)."/$cols rows";