-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.pl
More file actions
1641 lines (1348 loc) · 51.5 KB
/
table.pl
File metadata and controls
1641 lines (1348 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
#
# A filter to line up tables neatly - mainly for use from Vim
# Toby Thurston -- 27 Feb 2020
#
# 1. Read the data from stdin into a "table" object
# 2. Munge the table according to the supplied list of verbs+options
# 3. Print the table out again to stdout
#
# Usage: table delim verb [options] verb [options] ...
#
# Delimiter either specified or worked out from context if omitted
# Normally just ' ' but in tex: & and \cr; in latex & and \\; etc...
#
# Verbs: xp transpose rows and cells
# sort col-list sort by value of columns in the order given, use UPPERCASE to reverse
# uniq col-list filter rows to unique values in columns given
# add function add sum, mean, var, sd etc to foot of column
# arr col-list rearrange/insert/delete cols and/or do calculations on column values.
# dp dp-list round numbers in each col to specified decimal places
# sf sf-list round numbers in each col to specified significant figures
# reshape wide | long reshape table (for R etc)
# make tex | latex | plain | csv | tsv | md output in tex etc form
# label label columns with letters
# wrap n wrap columns in long table n times (default=2)
# unwrap n unwrap cols in wide table (default=half number of cols)
# zip n zip n rows together
# unzip n unzip into n * the current number of rows & 1/n columns.
#
# For full documentaion read (or better still extract) the POD at the end
use 5.008;
use strict;
use warnings;
use utf8; # for £ signs
use open qw[ :std :utf8 ];
use List::Util qw(min max sum shuffle);
use Math::Prime::Util qw(factor divisors);
use Math::Round qw(nearest);
use Math::SigFigs;
use POSIX qw(floor ceil);
use Statistics::Descriptive; # used for add functions
# following Cowlishaw, TRL p.136, but excluding octal (leading 0 and no point) but including 0 itself
# sign? mantissa--------------> exponent?
my $Number_atom = qr{ [-+]? (?:\d+\.\d*|\.\d+|0|[1-9]\d*) (?:E[-+]?\d+)? }ixmso;
my $Number_pattern = qr{\A $Number_atom \Z}ixmso;
my $Interval_pattern = qr{\A\( ( $Number_atom ) \, ( $Number_atom ) \)\Z}ixsmo;
my $Date_pattern = qr{\A ([12]\d\d\d)\D?([01]\d)\D?([0123]\d) \Z}ixmso; # make groups capture
my $Hrule_pattern = qr{\A -+ \Z}ixmso; # just a line of --------------
my $Trailing_number_pattern = qr{\A (.*\D) ($Number_atom) \Z}ixsmo;
my %Action_for = (
xp => \&transpose,
sort => \&sort_rows,
uniq => \&uniq_rows,
add => \&add_totals,
arr => \&arrange_cols,
make => \&set_output_form,
gen => \&append_new_rows,
dp => \&round_cols,
sf => \&sigfig_cols,
label => \&add_col_labels,
reshape => \&reshape_table,
reflow => \&reshape_table,
flow => \&reshape_table,
wrap => \&wrap_table,
unwrap => \&unwrap_table,
zip => \&zip_table,
unzip => \&unzip_table,
shuffle => \&shuffle_rows,
ditto => \©_down,
nospace => \&remove_spaces_from_cells,
);
# deal with the command line
my @agenda = ();
while (@ARGV) {
push @agenda, split q{ }, shift @ARGV;
}
my $delim = @agenda ? shift @agenda : 2;
my $separator;
if ($delim =~ /\A[1-9]\Z/xms) {
$separator = q{ } x $delim;
$delim = qr/\s{$delim,}/xms;
}
elsif ($delim =~ /\A[a-z]{2,}\Z/xms) {
unshift @agenda, $delim;
$separator = q{ };
$delim = qr/\s{2,}/xms;
}
elsif ($delim eq '|') {
$separator = '|';
$delim = qr/\|/xms;
}
elsif ($delim eq ',') {
$separator = ', ';
}
else {
$separator = qq{ $delim};
$delim = qr/$delim/xms;
}
my $indent = 0;
my $eol_marker = q{};
# Read the data from stdin unless it's connected to the terminal.
# For normal usage from Vim STDIN will *not* be connected to the terminal,
# but will have the input lines we need. For testing, we can run "perl table.pl"
# from the command line: in this situation we *don't* want to wait for STDIN.
my @input_lines = -t STDIN ? () : <STDIN>;
if (@input_lines) {
chomp(@input_lines);
# find the clear margin of blank space to the left of the table, ignoring any completely blank lines
$indent = min( map { /^(\s*)\S/; length($1) } grep { !/^\s*$/ } @input_lines ) || 0;
# recognize TeX and LateX delims automatically
if ($input_lines[0] =~ /\&.*(\\cr.*|\\\\.*)\Z/xms) {
$eol_marker = $1;
$delim = qr/\s*\&\s*/xms;
$separator = ' & ';
}
}
# split the input lines into cells in $Table->{data}
my @money_cols = ();
my $Table = { rows => 0, cols => 0 };
for (@input_lines) {
s/^\s*//; # remove leading space
s/\s*$//; # remove trailing space
s/\t/ /g; # remove tabs
if ( $eol_marker ne q{} ) {
$_ =~ s/\s*\Q$eol_marker\E\s*//iox;
}
if ( /^$/ || /$Hrule_pattern/ || /^\\noalign/ || /^\\intertext/ || /^\#/ ) {
push @{$Table->{specials}->[$Table->{rows}]}, $_;
next;
}
my @cells = $delim eq ',' ? csv_split($_) : split $delim;
my $i=0;
for (@cells) {
if (/^([£€]\s?)/) {
$money_cols[$i] ||= $1;
$_ =~ s/$1//;
}
else{
$money_cols[$i] ||= '0';
}
$i++;
}
push @{$Table->{data}}, \@cells ;
$Table->{rows}++;
$Table->{cols} = max($Table->{cols},scalar @cells);
}
# work through the list of verbs
while (@agenda) {
my $verb = lc shift @agenda;
my $option = @agenda ? shift @agenda : undef;
if ( defined $option && exists $Action_for{lc $option}) {
unshift @agenda, $option;
$option = undef;
}
if ( exists $Action_for{$verb} ) {
$Action_for{$verb}->($option)
}
else {
warn "> $verb is not defined. Try one of:\n";
warn join " ", ">", keys %Action_for, "\n";
}
}
# work out the widths and alignments, and add back any required £ signs
my @widths = (0) x $Table->{cols};
my @aligns = (0) x $Table->{cols};
for (my $c=0; $c<$Table->{cols}; $c++ ) {
for (my $r=0; $r<$Table->{rows}; $r++ ) {
next unless defined $Table->{data}->[$r][$c];
if ( decomma($Table->{data}->[$r][$c]) =~ $Number_pattern ) {
$aligns[$c]++;
if (defined $money_cols[$c] && $money_cols[$c] ne '0') {
$Table->{data}->[$r][$c] = $money_cols[$c] . $Table->{data}->[$r][$c];
}
}
else {
$aligns[$c]--;
}
$widths[$c] = max($widths[$c], length $Table->{data}->[$r][$c]);
}
}
my $table_width = sum(0,@widths) + length($separator) * ($Table->{cols}-1);
for (my $c=0; $c<$Table->{cols}; $c++ ) {
$widths[$c] *= -1 if $aligns[$c] < 0;
}
# print the table to stdout
for (my $r=0; $r<$Table->{rows}; $r++ ) {
if ( defined $Table->{specials}->[$r] ) {
for my $special_line ( @{$Table->{specials}->[$r]} ) {
print q{ } x $indent;
if ($special_line =~ $Hrule_pattern) {
if ($eol_marker eq '\\cr') {
print '\\noalign{\\vskip2pt\\hrule\\vskip4pt}' ; # auto convert ---- to tex rule
}
else {
print '-' x $table_width; # expand or shrink -------- lines
}
}
else {
print $special_line;
}
print "\n";
}
}
my $out = q{ } x $indent;
for (my $c=0; $c<$Table->{cols}; $c++ ) {
if (defined $Table->{data}->[$r][$c]) {
my $val = $Table->{data}->[$r][$c];
my $wd = $separator eq q{,} ? length($val) :
$separator eq "\t" ? length($val) :
$widths[$c];
if ( $separator eq q{,} && index($val,$separator)>0) {
$val = q{"} . $val . q{"};
}
$out .= sprintf "%*s", $wd, $val;
}
$out .= $separator;
}
$out =~ s/\Q$separator\E\Z/ $eol_marker/;
if ($separator eq '<td>') { # hack for html form
$out = "<tr><td>$out";
}
# remove any trailing white space (always irritating)
$out =~ s/\s*$//;
print $out, "\n";
}
exit 0;
sub csv_split {
my $input = shift;
my @out = ();
my $in_quote = 0;
my $field = '';
for my $c ( split //, $input ) {
if ($c eq ',' && !$in_quote) {
$field =~ s/^\s*//;
$field =~ s/\s*$//;
$field =~ s/^"//;
$field =~ s/"$//;
push @out, $field;
$field = '';
next;
}
if ($c eq '"') {
$in_quote = 1 - $in_quote;
}
$field .= $c;
}
$field =~ s/^\s*//;
$field =~ s/\s*$//;
$field =~ s/^"//;
$field =~ s/"$//;
push @out, $field;
return @out;
}
sub set_output_form {
my $form_name = shift;
if ($form_name eq "tex") { $separator = ' & '; $eol_marker = '\\cr' }
elsif ($form_name eq "latex") { $separator = ' & '; $eol_marker = '\\\\' }
elsif ($form_name eq "md") { $separator = ' | '; $eol_marker = q{} }
elsif ($form_name eq "csv") { $separator = q{,} ; $eol_marker = q{} }
elsif ($form_name eq "tsv") { $separator = "\t" ; $eol_marker = q{} }
elsif ($form_name eq "html") { $separator = '<td>'; $eol_marker = q{} }
elsif ($form_name eq "debug") { $separator = ' ! '; $eol_marker = '<<' }
else { $separator = q{ }; $eol_marker = q{} }
}
sub transpose {
my @transposed_tab;
for my $row (@{$Table->{data}}) {
for my $i (0 .. $Table->{cols}-1) {
push(@{$transposed_tab[$i]}, $row->[$i] );
}
}
$Table->{data} = \@transposed_tab;
@$Table{'rows','cols'} = @$Table{'cols','rows'};
}
# filter on unique combination of values in colums abc...
sub uniq_rows {
my $cols = shift; my @cols;
if (!$cols) { @cols = 0 .. $Table->{cols}-1 }
else {
for my $c (split //, $cols) {
if ( $c =~ /^[a-z]$/) {
my $i = ord($c)-ord('a');
if ($i < $Table->{cols}) {
push @cols, $i;
}
}
}
}
if (@cols) {
my %seen;
my @unique_rows;
for my $r (@{$Table->{data}}) {
my $key = join '\x01', @$r[@cols];
if (! exists $seen{$key}) {
$seen{$key} = 1;
push @unique_rows, $r;
}
}
$Table->{data} = \@unique_rows;
$Table->{rows} = scalar @unique_rows;
}
}
# Sort by column. Create an extra temp col with "arr" for fancy sorting.
sub sort_rows {
my $col_list = shift || 'a';
if ($col_list =~ m{[a-zA-Z]+}xmsio) {
for my $c (reverse split //, $col_list) {
sort_rows_by_column($c)
}
}
else {
sort_rows_by_column($col_list)
}
}
sub sort_rows_by_column {
my $col = shift;
my $reverse = 0;
if (!$col) { $col = 0 }
elsif ($col =~ /^[a-z]$/) { $col = ord($col)-ord('a') }
elsif ($col =~ /^[A-Z]$/) { $col = ord($col)-ord('A'); $reverse++ }
elsif ($col =~ /^\d+$/) { $col -= 1 } # 0 indexed
elsif ($col =~ /^-\d+$/) { $col = $Table->{cols}+1+$col }
else { $col = 0 }
# check bounds
$col = $col >= $Table->{cols} ? $Table->{cols}-1
: $col < 0 ? 0
: $col;
my @sorted;
if ($reverse) {
@sorted = map { $_->[0] }
sort { $b->[1] <=> $a->[1] || $b->[2] cmp $a->[2] }
map { [$_, as_number_reversed($_->[$col]), as_seminumeric_string($_->[$col])] } @{$Table->{data}};
}
else {
@sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] || $a->[2] cmp $b->[2] }
map { [$_, as_number($_->[$col]), as_seminumeric_string($_->[$col])] } @{$Table->{data}};
} # or "" to allow for blank cells...
$Table->{data} = \@sorted;
}
sub as_number {
my ($s) = @_;
return 1e9 unless defined $s;
return $s if $s =~ $Number_pattern;
if ($s =~ m{\A\d\d\D\d\d\D\d\d\d\d\Z}) {
$s = etos($s);
$s =~ s/-//g;
return $s;
}
return -1e9;
}
sub as_seminumeric_string {
my ($s) = @_;
# treat null as blank
return '' unless defined $s;
# pad trailing numbers with zeros
my $alpha;
my $numeric;
if (($alpha, $numeric) = $s =~ $Trailing_number_pattern) {
return sprintf "%s %09d", uc($alpha), $numeric;
}
# otherwise just upper case it...
return uc($s);
}
sub as_number_reversed {
my ($s) = @_;
return -1e9 unless defined $s;
return $s if $s =~ $Number_pattern;
if ($s =~ m{\A\d\d\D\d\d\D\d\d\d\d\Z}) {
$s = etos($s);
$s =~ s/-//g;
return $s;
}
return 1e9;
}
sub add_col_labels {
# add a row of labels for each column
my $label = 'a';
my @labels = ();
for (1..$Table->{cols}) {
push @labels, $label++;
}
$Table->{rows} = unshift @{$Table->{data}}, [ @labels ];
}
sub add_totals {
# Add values of function to bottom of cols
my $expr = shift || "sum";
if ($expr eq "var") {
$expr = "variance"
}
elsif ($expr eq "sd") {
$expr = "standard_deviation"
}
my @new_stats_row = ();
my $stat = Statistics::Descriptive::Full->new();
for (my $c = 0; $c < $Table->{cols}; $c++ ) {
$stat->clear();
for (my $r = 0; $r < $Table->{rows}; $r++ ) {
my $s = $Table->{data}->[$r][$c];
if (defined $s) {
if ($s =~ $Number_pattern) {
$stat->add_data($s);
}
elsif ($s =~ /negative\(($Number_atom)\)/ ) {
$stat->add_data(-$1)
}
}
}
my $value = $expr;
if ( $stat->count > 0 ) {
if ( $expr =~ m{\A([a-z_]+)\((\d+)\)\Z}ixmso ) {
$value = $stat->$1($2);
}
else {
$value = $stat->$expr;
}
}
push @new_stats_row, $value;
}
push @{$Table->{data}}, [ @new_stats_row ];
$Table->{rows}++;
}
sub append_new_rows {
my $sequence_or_number = shift || "Nothing";
my $alpha = 1;
my $omega = 10;
if ( $sequence_or_number =~ m{\A-?\d+\Z}ixmso ) {
$omega = $sequence_or_number;
}
elsif ( $sequence_or_number =~ m{\A(-?\d+)[^-0-9]+(-?\d+)\Z} ) {
$alpha = $1;
$omega = $2;
}
if ($alpha > $omega) {
($omega, $alpha) = ($alpha, $omega);
}
for my $n ($alpha .. $omega) {
push @{$Table->{data}}, [ ($n) ];
$Table->{rows}++;
}
$Table->{cols} = max(1, $Table->{cols});
}
sub shuffle_rows {
$Table->{data} = [ shuffle @{$Table->{data}} ];
}
sub reshape_table {
my $direction = shift;
return if $Table->{cols}<3; # do nothing on thin tables
if ( $direction eq "long" ) {
make_long_table()
}
elsif ( $direction eq "wide" ) {
make_wide_table()
}
else {
if ($Table->{cols}==3) {
make_wide_table()
}
else {
make_long_table()
}
}
}
sub make_long_table {
my @long_tab = ();
my $header_row = shift @{$Table->{data}};
push @long_tab, [ ($header_row->[0], 'Key', 'Value') ];
for my $row ( @{$Table->{data}} ) {
my $group_value = $row->[0];
for my $i (1..(@$row-1) ) {
push @long_tab, [ ( $group_value, $header_row->[$i], $row->[$i] ) ];
}
}
$Table->{data} = \@long_tab;
$Table->{rows} = scalar @long_tab;
$Table->{cols} = 3;
}
sub make_wide_table {
my $header_row = shift @{$Table->{data}};
my %values = ();
my @keys = ();
my %seen = ();
for my $row ( @{$Table->{data}} ) {
my ($x, $y, $value) = @$row;
$values{$x}{$y} = $value;
push @keys, $y unless $seen{$y}++;
}
my @wide_tab = ();
push @wide_tab, [ ($header_row->[0], @keys) ];
for my $x ( sort keys %values ) {
my @row = ( $x );
for my $y ( @keys ) {
push @row, $values{$x}{$y} || '0'
}
push @wide_tab, [ @row ];
}
$Table->{data} = \@wide_tab;
$Table->{rows} = scalar @wide_tab;
$Table->{cols} = 1 + scalar @keys;
}
sub sigfig_cols {
my $sf_string = shift;
# no-op unless we have a string of numbers
return unless defined $sf_string && $sf_string =~ m{\A \d+ \Z}xims;
# extend short string by repeating last digit
my $lsf = length($sf_string);
if ($lsf < $Table->{cols}) {
$sf_string .= substr($sf_string, -1) x ($Table->{cols}-$lsf);
}
for my $row (@{$Table->{data}}) {
my $i = 0;
for my $cell (@{$row}) {
my $sf = substr $sf_string, $i++, 1;
next if !defined $cell;
if ( $cell =~ $Number_pattern ) {
$cell = FormatSigFigs($cell,$sf);
}
elsif ( $cell =~ $Interval_pattern ) {
$cell = sprintf "(%s,%s)", FormatSigFigs($1,$sf), FormatSigFigs($2,$sf);
}
}
}
}
sub round_cols {
my $dp_string = shift;
# no-op unless we have a string of numbers
return unless defined $dp_string && $dp_string =~ m{\A \d+ \Z}xims;
# extend short string by repeating last digit
my $ldp = length($dp_string);
if ($ldp < $Table->{cols}) {
$dp_string .= substr($dp_string, -1) x ($Table->{cols}-$ldp);
}
for my $row (@{$Table->{data}}) {
my $i = 0;
for my $cell (@{$row}) {
my $dp = substr $dp_string, $i++, 1;
next if !defined $cell;
if ( $cell =~ $Number_pattern ) {
$cell = sprintf "%.${dp}f", $cell;
}
elsif ( $cell =~ $Interval_pattern ) {
$cell = sprintf "(%.${dp}f,%.${dp}f)", $1, $2;
}
}
}
}
sub comma {
my $cell = shift;
$cell = reverse $cell;
$cell =~ s/(\d\d\d)(?=\d)(?!\d*\.)/$1,/g;
return scalar reverse $cell;
}
sub decomma {
my $n = shift;
$n =~ s/,//g;
return $n;
}
sub copy_down {
for (my $r = 0; $r < $Table->{rows}; $r++ ) {
for (my $c=0; $c<$Table->{cols}; $c++ ) {
if (defined $Table->{data}->[$r]->[$c]
&& $r > 0
&& $Table->{data}->[$r]->[$c] eq q{"}) {
$Table->{data}->[$r]->[$c] = $Table->{data}->[$r-1]->[$c];
}
}
}
}
sub arrange_cols {
my $permutation = shift;
if ( $permutation =~ m{\A~} ) { # expand ~ to mean remaining cols
$permutation = substr('abcdefghijklmnopqrstuvwxyz',0,$Table->{cols})
. substr($permutation, 1);
}
elsif ( $permutation =~ m{~\Z} ) {
$permutation = substr($permutation, 0, -1)
. substr('abcdefghijklmnopqrstuvwxyz',0,$Table->{cols});
}
elsif ( $permutation =~ m{\A-([a-z]+)\Z} ) {
$permutation = substr('abcdefghijklmnopqrstuvwxyz',0,$Table->{cols});
$permutation =~ s/$1//;
}
return unless $permutation;
my %cumulative_sum_of = ();
for (my $r = 0; $r < $Table->{rows}; $r++ ) {
my $new_row_ref;
my %value_for = (); # build a hash of all the values
my $key = 'a'; # indexed by column letter
for (my $c=0; $c<$Table->{cols}; $c++ ) {
my $value = $Table->{data}->[$r]->[$c] || 0;
$cumulative_sum_of{$key} += $value if $value =~ m{$Number_pattern};
if ($value =~ /$Number_pattern/ && $value<0 ) {
$value = "($value)"
}
elsif ($value =~ /^([.1234567890]+)([BKMGT])$/ ) {
$value = sprintf "%g", $1 * (
$2 eq 'T' ? 1099511627776
: $2 eq 'G' ? 1073741824
: $2 eq 'M' ? 1048576
: $2 eq 'K' ? 1024
: 1);
}
elsif ($value !~ /$Number_pattern/) {
$value = "'$value'"
}
$value_for{$key} = $value;
# save the corresponding value in the line above
$value_for{'^' . $key} = $r==0 ? $value : $Table->{data}->[$r-1]->[$c] || 0;
$key++; # bump the column index
}
for my $m ( $permutation =~ m{[a-zA-Z1-9.?\$]|\{.*?\}}gxmso ) {
my $value;
if ($m =~ /^[a-z]$/) { $value = $Table->{data}->[$r]->[ord($m)-ord('a')] }
elsif ($m =~ /^[A-Z]$/) { $value = $cumulative_sum_of{lc $m} || $m }
elsif ($m eq q{.}) { $value = $r+1 }
elsif ($m eq q{$}) { $value = $Table->{rows} }
elsif ($m eq q{?}) { $value = rand()-0.5 }
else {
# strip {} from expr
$m =~ s/^\{//; $m =~ s/\}$//;
# substitute cell values (and don't bother checking for out of range letters)
my @tokens = $m =~ m/\^?[a-z]+|[A-Z]+|./g;
for my $t (@tokens) {
if ( exists $value_for{$t} ) {
$t = $value_for{$t}
}
elsif ( exists $cumulative_sum_of{lc $t} ) {
$t = $cumulative_sum_of{lc $t}
}
elsif ( $t eq "_" ) {
$t = ".' '."
}
elsif ( $t eq "=" ) {
$t = " eq "
}
}
# evaluate & replace answer with expression on error
$value = eval join '', @tokens;
$value = $m if $@;
}
push @$new_row_ref, $value;
}
$Table->{data}->[$r] = $new_row_ref;
}
$Table->{cols} = scalar @{$Table->{data}->[0]};
}
sub wrap_table {
my $n = shift || 2;
return unless $n > 1;
return unless $n < $Table->{rows}*$Table->{cols};
my @wide_tab = ();
my $new_cols = $Table->{cols} * $n;
my $new_rows = ceil($Table->{rows}/$n);
for (my $r=0; $r<$new_rows; $r++ ) {
my @new_row = ();
for (my $i=0; $i<$n; $i++ ) {
for (my $c=0; $c<$Table->{cols}; $c++ ) {
push @new_row, $Table->{data}->[$r+$i*$new_rows][$c];
}
}
push @wide_tab, [ @new_row ];
}
$Table->{data} = \@wide_tab;
$Table->{rows} = $new_rows;
$Table->{cols} = $new_cols;
}
sub unwrap_table {
my $n = shift || ceil($Table->{cols}/2);
return unless $n > 0;
return unless $n < $Table->{cols};
my @thin_tab = ();
my $new_cols = $n;
my $new_rows = ceil($Table->{rows}*$Table->{cols}/$n);
my $block = $n*$Table->{rows};
for (my $r=0; $r<$new_rows; $r++ ) {
my @new_row = ();
for (my $c=0; $c<$new_cols; $c++ ) {
my $cell_number = $r*$new_cols+$c;
my $old_r = int ($cell_number % $block)/$new_cols;
my $old_c = int ($cell_number / $block)*$new_cols + $cell_number % $new_cols;
push @new_row, $Table->{data}->[$old_r][$old_c];
}
push @thin_tab, [ @new_row ];
}
$Table->{data} = \@thin_tab;
$Table->{rows} = $new_rows;
$Table->{cols} = $new_cols;
}
sub zip_table {
my $n = shift || 2;
my @new_table = ();
my $new_cols = $Table->{cols} * $n;
my $new_rows = ceil($Table->{rows} / $n);
for (my $r=0; $r<$new_rows; $r++ ) {
my @new_row = ();
for (my $c=0; $c<$new_cols; $c++ ) {
my $old_r = $n*$r + floor($c / $Table->{cols});
my $old_c = $c % $Table->{cols};
push @new_row, $Table->{data}->[$old_r][$old_c];
}
push @new_table, [ @new_row ];
}
$Table->{data} = \@new_table;
$Table->{rows} = $new_rows;
$Table->{cols} = $new_cols;
}
sub unzip_table {
my $n = shift || 2;
my @new_table = ();
my $new_cols = ceil($Table->{cols} / $n);
my $new_rows = $Table->{rows} * $n;
for (my $r=0; $r<$new_rows; $r++ ) {
my @new_row = ();
for (my $c=0; $c<$new_cols; $c++ ) {
my $old_r = floor($r / $n);
my $old_c = $c + ($r % $n) * ceil($Table->{cols} / $n);
push @new_row, $Table->{data}->[$old_r][$old_c];
}
push @new_table, [ @new_row ];
}
$Table->{data} = \@new_table;
$Table->{rows} = $new_rows;
$Table->{cols} = $new_cols;
}
sub remove_spaces_from_cells {
my $joiner = shift || "";
for (my $r = 0; $r < $Table->{rows}; $r++ ) {
for (my $c=0; $c<$Table->{cols}; $c++ ) {
$Table->{data}->[$r]->[$c] =~ s/\s+/$joiner/g;
}
}
}
# Useful functions
sub round {
my ($n, $figs) = @_, 0;
return nearest(10**(-$figs), $n)
}
# Day of the week from base
sub dow {
my ($base) = @_;
if ($base =~ $Date_pattern ) {
$base = base($base);
}
if ($base =~ $Number_pattern) {
# Note that in Perl % always gives an integer even if base is a float
return qw(Mon Tue Wed Thu Fri Sat Sun)[$base%7]
}
return "DoW($base)";
}
# Convert dd/mm/yyyy to yyyy-mm-dd
sub etos {
my ($edate) = @_;
if ($edate =~ /([0123]\d)\D(0[1-9]|1[012])\D([12]\d\d\d)/) {
return date(base("$3-$2-$1"))
}
else {
return $edate;
}
}
#
# Convert mm/dd/yyyy to yyyy-mm-dd
sub utos {
my ($udate) = @_;
if ($udate =~ /(0?[1-9]|1[012])\/(0?\d|[12]\d|3[01])\/([12]\d\d\d)/) {
return date(base("$3-$1-$2"))
}
else {
return $udate;
}
}
sub base {
use integer;
my $date = shift;
my ($y,$m,$d);
if (!defined $date || $date eq q{}) {
(undef, undef, undef, $d, $m, $y) = localtime ;
$y += 1900;
$m -= 2;
}
elsif ($date =~ $Date_pattern ) {
($y, $m, $d) = ($1, $2, $3);
$m -=3;
}
else {
return "Base($date)";
}
while ($m<0) { $y-=1; $m+=12 }
while ($m>11) { $y+=1; $m-=12 }
my $base=365*$y + $y/4 - $y/100 + $y/400 + (2+3*$m)/5 + 30*$m + $d - 307;
return $base;
}
# Gregorian-ymd: returns "y-m-d" from a base number according
# to normal Gregorian calendar rules. Like date('s',base,'b')
# but allows for negative base numbers, and returns y m d as a
# list.
#
sub date {
use integer;
use Scalar::Util qw(looks_like_number);
my $d = shift || 0;
if (!looks_like_number($d)) {
return $d;
}
my ($y, $m) = (0,0);
$d = $d/1;
# Assume anything less than 1000 is a delta on today. (including negative numbers).
if ($d < 1000) {
$d += base();
}
my $s = $d/146097; $d=$d-$s*146097;
if ($d == 146096) { ($y, $m, $d) = ($s*400+400, 12, 31) } # special case 1
else {
my $c=$d/36524; $d=$d-$c*36524;
my $o=$d/1461; $d=$d-$o*1461;
if ( $d==1460) { ($y, $m, $d) = ($s*400+$c*100+$o*4+4, 12, 31) } # special case 2
else {
$y=$d/365; $d=$d-$y*365+1; # d is now in range 1-365
my @prior_days = ( $y==3 && ( $o < 24 || $c == 3 ) )
? (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 999)
: (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 999);
while ( $prior_days[$m] < $d) {
$m++;
}
$d = $d - $prior_days[$m-1];
$y = $s*400+$c*100+$o*4+$y+1;
}
}
return sprintf "%04d-%02d-%02d", $y, $m, $d;
}
# returns 01-12 from January-December
sub monthnumber {
my $s = shift;
my $m = index("JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC",uc(substr($s,0,3)));
return sprintf "%02d", $m/4+1;
}
sub hms {
my $s = shift;
my $H = floor($s/3600); $s = $s - 3600 * $H;
my $M = floor($s/60); $s = $s - 60 * $M;
my $S = floor($s); $s = $s - $S;
return sprintf "%02d:%02d:%02d", $H, $M, $S;
}
sub hmss {
use integer;
my $ms = shift;
my $H = $ms / 3600000; $ms = $ms - 3600000 * $H;
my $M = $ms / 60000; $ms = $ms - 60000 * $M;
my $S = $ms / 1000; $ms = $ms - 1000 * $S;
return sprintf "%02d:%02d:%02d.%03d", $H, $M, $S, $ms;
}
# parse a date into sortable form -- NB no _ in the function name
sub getbase {
my $s = shift;
if ( $s =~ $Date_pattern ) {
return base($s)
}
if ( $s =~ m{\A (\d+) \s ([a-z]+) \s ((?:19|20)\d\d) \Z}iosmx ) {
my $m = monthnumber($2);
my $d = sprintf "%02d", $1;
my $date = "$3-$m-$d";
return base($date);
}
if ( $s =~ m{\A (\d+)/([a-z]+)/((?:19|20)\d\d) \Z}iosmx ) {
my $m = monthnumber($2);
my $d = sprintf "%02d", $1;
my $date = "$3-$m-$d";
return base($date);
}
if ( $s =~ m{\A ([0123]\d) \D (0[1-9]|1[012]) \D ([12]\d\d\d) \Z}iosmx ) {
return base("$3-$2-$1");
}
if ( $s =~ m{\A([0123]\d)\D(0[1-9]|1[012])\D([012]\d) \Z}iosmx ) {
return base("20$3-$2-$1");
}
return $s;
}
sub makedate {
my $s = shift;
if ($s =~ m{\A \d+ \Z}iosmx) {
if ( $s > 1000000000000 ) {
return date(base("1970-01-01") + floor($s/86400000)) . " " . hmss($s % 86400000)
}
elsif ( $s > 1000000000 ) {
return date(base("1970-01-01") + floor($s/86400)) . " " . hms($s % 86400)
}
else {
return date($s)
}
}
return date(getbase($s))
}