-
Notifications
You must be signed in to change notification settings - Fork 1
/
columnStitch.pl
executable file
·2589 lines (2237 loc) · 85.1 KB
/
columnStitch.pl
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
#Note: 'use warnings' is below instead of having -w above
#Generated using perl_script_template.pl 2.4
#Robert W. Leach
#Center for Computational Research
#Copyright 2012
#These variables (in main) are used by getVersion() and usage()
my $software_version_number = '1.4';
my $created_on_date = '4/24/2012';
##
## Start Main
##
use warnings; #Same as using the -w, only just for code in this script
use strict;
use Getopt::Long qw(GetOptionsFromArray);
use File::Glob ':glob';
#This will allow us to track runtime warnings about undefined variables, etc.
local $SIG{__WARN__} = sub {my $err = $_[0];chomp($err);
warning("Runtime warning: [$err].")};
#Declare & initialize variables. Provide default values here.
my($outfile_suffix); #Not defined so input can be overwritten
my $input_files = [];
my $outdirs = [];
my $columns = [];
my $current_output_file = '';
my $help = 0;
my $version = 0;
my $overwrite = 0;
my $skip_existing = 0;
my $keep_infile_headers = 0;
my $header = 1;
my $error_limit = 50;
my $dry_run = 0;
my $use_as_default = 0;
my $defaults_dir = (sglob('~/.rpst'))[0];
my $delims = []; #Default: \t
#These variables (in main) are used by the following subroutines:
#verbose, error, warning, debug, getCommand, quit, and usage
my $preserve_args = [@ARGV]; #Preserve the agruments for getCommand
my $verbose = 0;
my $quiet = 0;
my $DEBUG = 0;
my $ignore_errors = 0;
my @user_defaults = getUserDefaults();
my $GetOptHash =
{'i|input-file=s' => sub {push(@$input_files, #REQUIRED unless <> is
[sglob($_[1])])}, # supplied
'<>' => sub {push(@$input_files, #REQUIRED unless -i is
[sglob($_[0])])}, # supplied
'c|columns=s' => sub {push(@$columns, #OPTIONAL [all cols]
[map {/(\d+)(?:\.\.|-)(\d+)/ ?
$1..$2 : $_}
split(/\s+/,$_[1])])},
'd|delimiter=s' => sub {push(@$delims, #OPTIONAL [\t]
$_[1])},
'o|outfile-suffix=s' => \$outfile_suffix, #OPTIONAL [undef]
'outdir=s' => sub {push(@$outdirs, #OPTIONAL
[sglob($_[1])])},
'force|overwrite' => \$overwrite, #OPTIONAL [Off]
'skip-existing!' => \$skip_existing, #OPTIONAL [Off]
'ignore' => \$ignore_errors, #OPTIONAL [Off]
'verbose:+' => \$verbose, #OPTIONAL [Off]
'quiet' => \$quiet, #OPTIONAL [Off]
'debug:+' => \$DEBUG, #OPTIONAL [Off]
'help' => \$help, #OPTIONAL [Off]
'version' => \$version, #OPTIONAL [Off]
'keep-infile-headers!' => \$keep_infile_headers, #OPTIONAL [Off]
'header!' => \$header, #OPTIONAL [On]
'error-type-limit=s' => \$error_limit, #OPTIONAL [0]
'dry-run!' => \$dry_run, #OPTIONAL [Off]
'use-as-default!' => \$use_as_default, #OPTIONAL [Off]
};
#If the user has previously stored any defaults
if(scalar(@user_defaults))
{
#Save the defaults, because GetOptionsFromArray alters the array
my @tmp_user_defaults = @user_defaults;
#Get any default values the user stored, set the default values before
#calling GetOptions using the real @ARGV array and before calling usage so
#that the user-defined default values will show in the usage output
GetOptionsFromArray(\@user_defaults,%$GetOptHash);
#Reset the user defaults array for later use
@user_defaults = @tmp_user_defaults;
}
#If there are no arguments and no files directed or piped in
if(scalar(@ARGV) == 0 && isStandardInputFromTerminal())
{
usage();
quit(0);
}
#Get the input options & catch any errors in option parsing
unless(GetOptions(%$GetOptHash))
{
#Try to guess which arguments GetOptions is complaining about
my @possibly_bad = grep {!(-e $_)} map {@$_} @$input_files;
error('Getopt::Long::GetOptions reported an error while parsing the ',
'command line arguments. The error should be above. Please ',
'correct the offending argument(s) and try again.');
usage(1);
quit(-1);
}
if(scalar(grep {$_} ($use_as_default,$help,$version)) > 1)
{
error("Options [",join(',',grep {$_} ($use_as_default,$help,$version)),
"] are mutually exclusive.");
quit(-20);
}
#If the user specified that they would like to use the current options as
#default values, store them
if($use_as_default)
{
if(saveUserDefaults($preserve_args))
{
print("Old user defaults: [",join(' ',@user_defaults),"].\n",
"New user defaults: [",join(' ',getUserDefaults()),"].\n");
quit(0);
}
else
{quit(-19)}
}
print STDERR ("Starting dry run.\n") if($dry_run);
#Print the debug mode (it checks the value of the DEBUG global variable)
debug('Debug mode on.') if($DEBUG > 1);
#If the user has asked for help, call the help subroutine
if($help)
{
help();
quit(0);
}
#If the user has asked for the software version, print it
if($version)
{
print(getVersion($verbose),"\n");
quit(0);
}
#Check validity of verbosity options
if($quiet && ($verbose || $DEBUG))
{
$quiet = 0;
error('You cannot supply the quiet and (verbose or debug) flags ',
'together.');
quit(-2);
}
#Check validity of existing outfile options
if($skip_existing && $overwrite)
{
error('You cannot supply the --overwrite and --skip-existing flags ',
'together.');
quit(-3);
}
#Warn users when they turn on verbose and output is to the terminal
#(implied by no outfile suffix checked above) that verbose messages may be
#uncleanly overwritten
if($verbose && !defined($outfile_suffix) && isStandardOutputToTerminal())
{warning('You have enabled --verbose, but appear to possibly be ',
'outputting to the terminal. Note that verbose messages can ',
'interfere with formatting of terminal output making it ',
'difficult to read. You may want to either turn verbose off, ',
'redirect output to a file, or supply an outfile suffix (-o).')}
#Make sure there is input
if(scalar(@$input_files) == 0 && isStandardInputFromTerminal())
{
error('No input files detected.');
usage(1);
quit(-4);
}
#Make sure that an outfile suffix has been supplied if an outdir has been
#supplied
if(scalar(@$outdirs) && !defined($outfile_suffix))
{
error("An outfile suffix (-o) is required if an output directory ",
"(--outdir) is supplied. Note, you may supply an empty string ",
"to name the output files the same as the input files.");
quit(-5);
}
if(scalar(@$delims) == 0)
{push(@$delims,"\t")}
if(scalar(@$delims) != 1 && scalar(@$delims) != scalar(@$input_files))
{
error("The number of delimiters supplied (-d) [",scalar(@$delims),
"] must be either 1 or the same number of types of input files ",
"supplied [",scalar(@$input_files),"].");
quit(1);
}
#Get all the corresponding groups of files and output directories to process
my($input_file_sets,
$outfile_stub_sets) = getFileSets((map {[$_]} @$input_files),
$outdirs);
#Look for existing output files generated by the input_files array
#Note, the index for the submitted array is determined by the position of the
#input_files array in the call to getFileSets
my(@existing_outfiles);
my @tmp_existing_outfiles = getExistingOutfiles($outfile_stub_sets->[0],
$outfile_suffix);
push(@existing_outfiles,@tmp_existing_outfiles)
if(scalar(@tmp_existing_outfiles));
#If any of the expected output files already exist, quit with an error
if(scalar(@existing_outfiles) && !$overwrite && !$skip_existing)
{
error("Files exist: [",join(',',@existing_outfiles),"].\nUse --overwrite ",
'or --skip-existing to continue.');
quit(-6);
}
my $indexes = [];
if(scalar(@$columns))
{
if(scalar(@$columns) < scalar(@$input_files))
{
error("There were [",scalar(@$columns),"] column flags supplied and [",
scalar(@$input_files),"] file flags (including STDIN) ",
"supplied. There must be at least as many column flags as ",
"file flags supplied. If you want all columns from a specific ",
"set of input files, you must supply an empty string, e.g. -c ",
"''.");
quit(1);
}
#If the columns are all indicated by number, set the indexes
if(scalar(grep {/\D/} map {@$_} @$columns) == 0)
{foreach my $col_set (@$columns)
{push(@$indexes,[map {$_ ne '' ? $_ - 1 : $_} @$col_set])}}
else
{
debug("By-name mode on.");
foreach my $col_set (@$columns)
{push(@$indexes,[@$col_set])}
}
}
else
{
#Assume we're merging the files in order, so enter an empty string for each
#input file set
@$indexes = map {['']} @$input_files;
}
my $index_by_name = 0;
#If the columns are indicated by column header, set the indexes by looking at
#the first line in each file that has the delimiter
if(scalar(grep {/\D/} map {@$_} @$columns))
{$index_by_name = 1}
#Create the output directories
mkdirs(@$outdirs);
verbose('Run conditions: ',getCommand(1));
#If output is going to STDOUT instead of output files with different extensions
#or if STDOUT was redirected, output run info once
verbose('[STDOUT] Opened for all output.') if(!defined($outfile_suffix));
#Store info. about the run as a comment at the top of the output file if
#STDOUT has been redirected to a file
if(!isStandardOutputToTerminal() && $header)
{print(getVersion(),"\n",
'#',scalar(localtime($^T)),"\n",
'#',getCommand(1),"\n");}
my($delim,$delim_pat);
#For each set of input files associated by getFileSets
foreach my $set_num (0..$#$input_file_sets)
{
my @data = ();
$delim = shift(@$delims) if(scalar(@$delims));
$delim_pat = quotemeta($delim);
#Keep track of the largest number of columns per file
my @maxsizes = ();
debug("Using delimiter [$delim].");
my $outfile_stub = $outfile_stub_sets->[$set_num]->[0];
if(defined($outfile_suffix))
{
$current_output_file = $outfile_stub . $outfile_suffix;
checkFile($current_output_file,$input_file_sets->[$set_num]) || next;
openOut(*OUTPUT,$current_output_file) || next;
}
foreach my $file (@{$input_file_sets->[$set_num]})
{
openIn(*INPUT,$file) || next;
next if($dry_run);
push(@data,[]);
#Keep track of the largest number of columns per file
push(@maxsizes,0);
my $line_num = 0;
my $verbose_freq = 100;
#For each line in the current input file
while(getLine(*INPUT))
{
$line_num++;
verboseOverMe("[$file] Reading line: [$line_num].")
unless($line_num % $verbose_freq);
#If we're keeping the infile headers and this is a header line
if($keep_infile_headers && /^\s*#/)
{
#Print it unless it's an empty line
print;
#Let the tabbed line get stitched like the rest even though we
#just printed it as part of the infile header
next unless(/$delim_pat/);
}
elsif(/^\s*$/ || /^\s*#/)
{next}
chomp;
push(@{$data[-1]},[split(/$delim_pat/,$_,-1)]);
#Keep track of the largest number of columns for this file in case
#The user is merging all columns
if(scalar(@{$data[-1]->[-1]}) > $maxsizes[-1])
{$maxsizes[-1] = scalar(@{$data[-1]->[-1]})}
}
closeIn(*INPUT);
}
my $num_cols_pushed_on = 0;
my $file_index = 0;
my @out_data = ();
#For each set of indexes (indicating ordered columns from respctive input
#files (cycled in order)
foreach my $col_index_set (@$indexes)
{
next if($dry_run);
#Rotate through the types of files for each col_index_set
$file_index = $file_index % scalar(@{$input_file_sets->[$set_num]});
debug("Doing file index [$file_index].");
#For each column index we're to grab from this file
foreach my $col_id (@$col_index_set)
{
my($col_index);
if($index_by_name)
{
my @colheads = @{$data[$file_index]->[0]};
my $head_pat = quotemeta($col_id);
my @head_matches = grep {/^$head_pat$/} @colheads;
if(scalar(@head_matches) == 0)
{@head_matches = grep {/^$head_pat$/i} @colheads}
if(scalar(@head_matches) == 0)
{
@head_matches = grep {/$head_pat/i} @colheads;
warning("Had to use loose matching criteria to find the ",
"column header [$col_id].")
if(scalar(@head_matches));
}
if(scalar(@head_matches) == 0 && $col_id ne '0')
{
error("Unable to find column [$col_id] in file ",
"[$input_file_sets->[$set_num]->[$file_index]]. ",
"Skipping column.");
next;
}
if($col_id eq '0' && scalar(@head_matches) == 0)
{$col_index = ''}
else
{
$col_index = (grep {$colheads[$_] eq $head_matches[0]}
(0..$#colheads))[0];
debug("Matching header [$head_matches[0]].");
}
debug("Column index: [$col_index] matches column name ",
"[$col_id] among these column headers [@colheads].");
}
else
{$col_index = $col_id}
debug("Doing col index [$col_index].");
#If the user supplied an empty string, it means add all columns
if($col_index eq '')
{
my $max_num_cols = 0;
my $row_index = 0;
my $num_cols_hash = {};
foreach my $row_array (@{$data[$file_index]})
{
#If the out_data array doesn't have this row, push it on
unless(exists($out_data[$row_index]))
{
#Back-fill columns already pushed on w/ empty strings
if($num_cols_pushed_on)
{push(@out_data,[map {''} (1..$num_cols_pushed_on)])}
else
{push(@out_data,[])}
}
#Keep track of the maximum number of columns added
if(scalar(@$row_array) > $max_num_cols)
{$max_num_cols = scalar(@$row_array)}
$num_cols_hash->{scalar(@$row_array)}++;
#Push all the columns from this row on
push(@{$out_data[$row_index]},@$row_array);
$row_index++;
}
#If the number of columns was not consistent, issue an error
if(scalar(keys(%$num_cols_hash)) > 1)
{
warning("The number of columns in ",
"[$input_file_sets->[$set_num]->[$file_index]] ",
"is inconsistent. The numbers of columns are [",
join(', ',
map {"[$num_cols_hash->{$_}] rows with " .
"[$_] columns"}
keys(%$num_cols_hash)),"]. The missing ",
"columns will be filled in with empty strings.");
#Now go through and fix the columns
my $tot_num_cols = $num_cols_pushed_on + $max_num_cols;
my $rown = 1;
foreach my $out_row (@out_data)
{
if(scalar(@$out_row) > $tot_num_cols)
{error("Too many columns in row [$rown]. Should ",
"have [$tot_num_cols] but has [",
scalar(@$out_row),"].")}
debug("Row [$rown] has [",scalar(@$out_row),
"] columns and should have [$tot_num_cols].");
my $diff_num_cols = $tot_num_cols - scalar(@$out_row);
if($diff_num_cols > 0)
{
debug("Pushing [$diff_num_cols] empty strings ",
"onto row [$rown].");
push(@$out_row,map {''} (1..$diff_num_cols));
}
$rown++;
}
}
$num_cols_pushed_on += $max_num_cols;
next;
}
#Skip if the user supplied a 0 column number (indicating no cols)
next if($col_index ne '' && $col_index < 0);
my $row_index = 0;
foreach my $row_array (@{$data[$file_index]})
{
debug("Doing Row index [$row_index].");
#If the out_data array doesn't have this row yet, push it on
unless(exists($out_data[$row_index]))
{
#Back-fill columns already pushed on w/ empty strings
if($num_cols_pushed_on)
{push(@out_data,[map {''} (1..$num_cols_pushed_on)])}
else
{push(@out_data,[])}
}
#If this column exists in the input data, push it on
if(scalar(@$row_array) >= ($col_index + 1))
{push(@{$out_data[$row_index]},$row_array->[$col_index])}
else
{
warning("Column [",($col_index + 1),"] does not exist on ",
"row [",($row_index + 1),"] of file ",
"[$input_file_sets->[$set_num]->[$file_index]]: [",
join('|',@$row_array),"].");
push(@{$out_data[$row_index]},'');
}
$row_index++;
}
$num_cols_pushed_on++;
}
$file_index++;
}
print(join("\n",map {join($delim,@$_)} @out_data));
closeOut(*OUTPUT) if(defined($outfile_suffix));
}
verbose("[STDOUT] Output done.") if(!defined($outfile_suffix));
#Report the number of errors, warnings, and debugs on STDERR
printRunReport($verbose) if(!$quiet && ($verbose || $DEBUG ||
defined($main::error_number) ||
defined($main::warning_number)));
##
## End Main
##
##
## Subroutines
##
##
## Subroutine that prints formatted verbose messages. Specifying a 1 as the
## first argument prints the message in overwrite mode (meaning subsequence
## verbose, error, warning, or debug messages will overwrite the message
## printed here. However, specifying a hard return as the first character will
## override the status of the last line printed and keep it. Global variables
## keep track of print length so that previous lines can be cleanly
## overwritten.
##
sub verbose
{
return(0) unless($verbose);
#Read in the first argument and determine whether it's part of the message
#or a value for the overwrite flag
my $overwrite_flag = $_[0];
#If a flag was supplied as the first parameter (indicated by a 0 or 1 and
#more than 1 parameter sent in)
if(scalar(@_) > 1 && ($overwrite_flag eq '0' || $overwrite_flag eq '1'))
{shift(@_)}
else
{$overwrite_flag = 0}
# #Ignore the overwrite flag if STDOUT will be mixed in
# $overwrite_flag = 0 if(isStandardOutputToTerminal());
#Read in the message
my $verbose_message = join('',grep {defined($_)} @_);
$overwrite_flag = 1 if(!$overwrite_flag && $verbose_message =~ /\r/);
#Initialize globals if not done already
$main::last_verbose_size = 0 if(!defined($main::last_verbose_size));
$main::last_verbose_state = 0 if(!defined($main::last_verbose_state));
$main::verbose_warning = 0 if(!defined($main::verbose_warning));
#Determine the message length
my($verbose_length);
if($overwrite_flag)
{
$verbose_message =~ s/\r$//;
if(!$main::verbose_warning && $verbose_message =~ /\n|\t/)
{
warning('Hard returns and tabs cause overwrite mode to not work ',
'properly.');
$main::verbose_warning = 1;
}
}
else
{chomp($verbose_message)}
#If this message is not going to be over-written (i.e. we will be printing
#a \n after this verbose message), we can reset verbose_length to 0 which
#will cause $main::last_verbose_size to be 0 the next time this is called
if(!$overwrite_flag)
{$verbose_length = 0}
#If there were \r's in the verbose message submitted (after the last \n)
#Calculate the verbose length as the largest \r-split string
elsif($verbose_message =~ /\r[^\n]*$/)
{
my $tmp_message = $verbose_message;
$tmp_message =~ s/.*\n//;
($verbose_length) = sort {length($b) <=> length($a)}
split(/\r/,$tmp_message);
}
#Otherwise, the verbose_length is the size of the string after the last \n
elsif($verbose_message =~ /([^\n]*)$/)
{$verbose_length = length($1)}
#If the buffer is not being flushed, the verbose output doesn't start with
#a \n, and output is to the terminal, make sure we don't over-write any
#STDOUT output
#NOTE: This will not clean up verbose output over which STDOUT was written.
#It will only ensure verbose output does not over-write STDOUT output
#NOTE: This will also break up STDOUT output that would otherwise be on one
#line, but it's better than over-writing STDOUT output. If STDOUT is going
#to the terminal, it's best to turn verbose off.
if(!$| && $verbose_message !~ /^\n/ && isStandardOutputToTerminal())
{
#The number of characters since the last flush (i.e. since the last \n)
#is the current cursor position minus the cursor position after the
#last flush (thwarted if user prints \r's in STDOUT)
#NOTE:
# tell(STDOUT) = current cursor position
# sysseek(STDOUT,0,1) = cursor position after last flush (or undef)
my $num_chars = sysseek(STDOUT,0,1);
if(defined($num_chars))
{$num_chars = tell(STDOUT) - $num_chars}
else
{$num_chars = 0}
#If there have been characters printed since the last \n, prepend a \n
#to the verbose message so that we do not over-write the user's STDOUT
#output
if($num_chars > 0)
{$verbose_message = "\n$verbose_message"}
}
#Overwrite the previous verbose message by appending spaces just before the
#first hard return in the verbose message IF THE VERBOSE MESSAGE DOESN'T
#BEGIN WITH A HARD RETURN. However note that the length stored as the
#last_verbose_size is the length of the last line printed in this message.
if($verbose_message =~ /^([^\n]*)/ && $main::last_verbose_state &&
$verbose_message !~ /^\n/)
{
my $append = ' ' x ($main::last_verbose_size - length($1));
unless($verbose_message =~ s/\n/$append\n/)
{$verbose_message .= $append}
}
#If you don't want to overwrite the last verbose message in a series of
#overwritten verbose messages, you can begin your verbose message with a
#hard return. This tells verbose() to not overwrite the last line that was
#printed in overwrite mode.
#Print the message to standard error
print STDERR ($verbose_message,
($overwrite_flag ? "\r" : "\n"));
#Record the state
$main::last_verbose_size = $verbose_length;
$main::last_verbose_state = $overwrite_flag;
#Return success
return(0);
}
sub verboseOverMe
{verbose(1,@_)}
##
## Subroutine that prints errors with a leading program identifier containing a
## trace route back to main to see where all the subroutine calls were from,
## the line number of each call, an error number, and the name of the script
## which generated the error (in case scripts are called via a system call).
## Globals used defined in main: error_limit, quiet, verbose
## Globals used defined in here: error_hash, error_number
## Globals used defined in subs: last_verbose_state, last_verbose_size
##
sub error
{
return(0) if($quiet);
#Gather and concatenate the error message and split on hard returns
my @error_message = split(/\n/,join('',grep {defined($_)} @_));
push(@error_message,'') unless(scalar(@error_message));
pop(@error_message) if(scalar(@error_message) > 1 &&
$error_message[-1] !~ /\S/);
$main::error_number++;
my $leader_string = "ERROR$main::error_number:";
#Assign the values from the calling subroutines/main
my(@caller_info,$line_num,$caller_string,$stack_level,$script);
#Build a trace-back string. This will be used for tracking the number of
#each type of error as well as embedding into the error message in debug
#mode.
$script = $0;
$script =~ s/^.*\/([^\/]+)$/$1/;
@caller_info = caller(0);
$line_num = $caller_info[2];
$caller_string = '';
$stack_level = 1;
while(@caller_info = caller($stack_level))
{
my $calling_sub = $caller_info[3];
$calling_sub =~ s/^.*?::(.+)$/$1/ if(defined($calling_sub));
$calling_sub = (defined($calling_sub) ? $calling_sub : 'MAIN');
$caller_string .= "$calling_sub(LINE$line_num):"
if(defined($line_num));
$line_num = $caller_info[2];
$stack_level++;
}
$caller_string .= "MAIN(LINE$line_num):";
if($DEBUG)
{$leader_string .= "$script:$caller_string"}
$leader_string .= ' ';
my $leader_length = length($leader_string);
#Figure out the length of the first line of the error
my $error_length = length(($error_message[0] =~ /\S/ ?
$leader_string : '') .
$error_message[0]);
#Clean up any previous verboseOverMe output that may be longer than the
#first line of the error message, put leader string at the beginning of
#each line of the message, and indent each subsequent line by the length
#of the leader string
my $error_string = $leader_string . shift(@error_message) .
($verbose && defined($main::last_verbose_state) &&
$main::last_verbose_state ?
' ' x ($main::last_verbose_size - $error_length) : '') . "\n";
foreach my $line (@error_message)
{$error_string .= (' ' x $leader_length) . $line . "\n"}
#If the global error hash does not yet exist, store the first example of
#this error type
if(!defined($main::error_hash) ||
!exists($main::error_hash->{$caller_string}))
{
$main::error_hash->{$caller_string}->{EXAMPLE} = $error_string;
$main::error_hash->{$caller_string}->{EXAMPLENUM} =
$main::error_number;
$main::error_hash->{$caller_string}->{EXAMPLE} =~ s/\n */ /g;
$main::error_hash->{$caller_string}->{EXAMPLE} =~ s/ $//g;
$main::error_hash->{$caller_string}->{EXAMPLE} =~ s/^(.{100}).+/$1.../;
}
#Increment the count for this error type
$main::error_hash->{$caller_string}->{NUM}++;
#Print the error unless it is over the limit for its type
if($error_limit == 0 ||
$main::error_hash->{$caller_string}->{NUM} <= $error_limit)
{
print STDERR ($error_string);
#Let the user know if we're going to start suppressing errors of this
#type
if($error_limit &&
$main::error_hash->{$caller_string}->{NUM} == $error_limit)
{print STDERR ($leader_string,"NOTE: Further errors of this type ",
"will be suppressed.\n$leader_string",
"Set --error-type-limit to 0 to turn off error ",
"suppression\n")}
}
#Reset the verbose states if verbose is true
if($verbose)
{
$main::last_verbose_size = 0;
$main::last_verbose_state = 0;
}
#Return success
return(0);
}
##
## Subroutine that prints warnings with a leader string containing a warning
## number
##
## Globals used defined in main: error_limit, quiet, verbose
## Globals used defined in here: warning_hash, warning_number
## Globals used defined in subs: last_verbose_state, last_verbose_size
##
sub warning
{
return(0) if($quiet);
$main::warning_number++;
#Gather and concatenate the warning message and split on hard returns
my @warning_message = split(/\n/,join('',grep {defined($_)} @_));
push(@warning_message,'') unless(scalar(@warning_message));
pop(@warning_message) if(scalar(@warning_message) > 1 &&
$warning_message[-1] !~ /\S/);
my $leader_string = "WARNING$main::warning_number:";
#Assign the values from the calling subroutines/main
my(@caller_info,$line_num,$caller_string,$stack_level,$script);
#Build a trace-back string. This will be used for tracking the number of
#each type of warning as well as embedding into the warning message in
#debug mode.
$script = $0;
$script =~ s/^.*\/([^\/]+)$/$1/;
@caller_info = caller(0);
$line_num = $caller_info[2];
$caller_string = '';
$stack_level = 1;
while(@caller_info = caller($stack_level))
{
my $calling_sub = $caller_info[3];
$calling_sub =~ s/^.*?::(.+)$/$1/ if(defined($calling_sub));
$calling_sub = (defined($calling_sub) ? $calling_sub : 'MAIN');
$caller_string .= "$calling_sub(LINE$line_num):"
if(defined($line_num));
$line_num = $caller_info[2];
$stack_level++;
}
$caller_string .= "MAIN(LINE$line_num):";
if($DEBUG)
{$leader_string .= "$script:$caller_string"}
$leader_string .= ' ';
my $leader_length = length($leader_string);
#Figure out the length of the first line of the error
my $warning_length = length(($warning_message[0] =~ /\S/ ?
$leader_string : '') .
$warning_message[0]);
#Clean up any previous verboseOverMe output that may be longer than the
#first line of the warning message, put leader string at the beginning of
#each line of the message and indent each subsequent line by the length
#of the leader string
my $warning_string =
$leader_string . shift(@warning_message) .
($verbose && defined($main::last_verbose_state) &&
$main::last_verbose_state ?
' ' x ($main::last_verbose_size - $warning_length) : '') .
"\n";
foreach my $line (@warning_message)
{$warning_string .= (' ' x $leader_length) . $line . "\n"}
#If the global warning hash does not yet exist, store the first example of
#this warning type
if(!defined($main::warning_hash) ||
!exists($main::warning_hash->{$caller_string}))
{
$main::warning_hash->{$caller_string}->{EXAMPLE} = $warning_string;
$main::warning_hash->{$caller_string}->{EXAMPLENUM} =
$main::warning_number;
$main::warning_hash->{$caller_string}->{EXAMPLE} =~ s/\n */ /g;
$main::warning_hash->{$caller_string}->{EXAMPLE} =~ s/ $//g;
$main::warning_hash->{$caller_string}->{EXAMPLE} =~
s/^(.{100}).+/$1.../;
}
#Increment the count for this warning type
$main::warning_hash->{$caller_string}->{NUM}++;
#Print the warning unless it is over the limit for its type
if($error_limit == 0 ||
$main::warning_hash->{$caller_string}->{NUM} <= $error_limit)
{
print STDERR ($warning_string);
#Let the user know if we're going to start suppressing warnings of this
#type
if($error_limit &&
$main::warning_hash->{$caller_string}->{NUM} == $error_limit)
{print STDERR ($leader_string,"NOTE: Further warnings of this ",
"type will be suppressed.\n$leader_string",
"Set --error-type-limit to 0 to turn off error ",
"suppression\n")}
}
#Reset the verbose states if verbose is true
if($verbose)
{
$main::last_verbose_size = 0;
$main::last_verbose_state = 0;
}
#Return success
return(0);
}
##
## Subroutine that gets a line of input and accounts for carriage returns that
## many different platforms use instead of hard returns. Note, it uses a
## global array reference variable ($infile_line_buffer) to keep track of
## buffered lines from multiple file handles.
##
sub getLine
{
my $file_handle = $_[0];
#Set a global array variable if not already set
$main::infile_line_buffer = {} if(!defined($main::infile_line_buffer));
if(!exists($main::infile_line_buffer->{$file_handle}))
{$main::infile_line_buffer->{$file_handle}->{FILE} = []}
#If this sub was called in array context
if(wantarray)
{
#Check to see if this file handle has anything remaining in its buffer
#and if so return it with the rest
if(scalar(@{$main::infile_line_buffer->{$file_handle}->{FILE}}) > 0)
{
return(@{$main::infile_line_buffer->{$file_handle}->{FILE}},
map
{
#If carriage returns were substituted and we haven't
#already issued a carriage return warning for this file
#handle
if(s/\r\n|\n\r|\r/\n/g &&
!exists($main::infile_line_buffer->{$file_handle}
->{WARNED}))
{
$main::infile_line_buffer->{$file_handle}->{WARNED}
= 1;
warning('Carriage returns were found in your file ',
'and replaced with hard returns.');
}
split(/(?<=\n)/,$_);
} <$file_handle>);
}
#Otherwise return everything else
return(map
{
#If carriage returns were substituted and we haven't already
#issued a carriage return warning for this file handle
if(s/\r\n|\n\r|\r/\n/g &&
!exists($main::infile_line_buffer->{$file_handle}
->{WARNED}))
{
$main::infile_line_buffer->{$file_handle}->{WARNED}
= 1;
warning('Carriage returns were found in your file ',
'and replaced with hard returns.');
}
split(/(?<=\n)/,$_);
} <$file_handle>);
}
#If the file handle's buffer is empty, put more on
if(scalar(@{$main::infile_line_buffer->{$file_handle}->{FILE}}) == 0)
{
my $line = <$file_handle>;
#The following is to deal with files that have the eof character at the
#end of the last line. I may not have it completely right yet.
if(defined($line))
{
if($line =~ s/\r\n|\n\r|\r/\n/g &&
!exists($main::infile_line_buffer->{$file_handle}->{WARNED}))
{
$main::infile_line_buffer->{$file_handle}->{WARNED} = 1;