blib/lib/Describe.pm untested

filter: Statementstmt 0.0% 0 / 455 Branchbran 0.0% 0 / 296 Conditioncond 0.0% 0 / 144 MC/DCmcdc 0.0% 0 / 89 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 1039 CC 149 SCAR 70.9
CC
149
Cov
0%
describe
2970.0
get_date_format
1056.0
output
702.0
CRAP 1194.1
1 package Data::Describe;
2  
3 use strict;
4 use vars qw($AUTOLOAD);
5 use Carp;
6 use warnings;
7  
8 # require Exporter;
9  
10 use IO::File;
11 use File::Basename;
12 # use Fax::DataFax::DateTime qw(get_date_format);
13  
14 # This allows declaration use DataFax ':all';
15 # If you do not need this, moving things directly into @EXPORT or
16 # @EXPORT_OK will save memory.
17 our @ISA;
18 our %EXPORT_TAGS = ( 'all' => [ qw(describe) ] );
19 our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
20 our @EXPORT = qw( );
21 our $VERSION = '1.03';
22  
23 =head1 NAME
24  
25 Data::Describe - Perl extension for scanning/describing a text file
26 or array.
27  
28 =head1 SYNOPSIS
29  
30 use Data::Describe;
31  
32 $dsp = Data::Describe->new; # create an empty object
33 my %arg = ( input_file_name => 'input.txt', # the same as 'ifn'
34 skip_first_row => 'Y', # the same as 'sfr'
35 input_field_sep => ',', # the same as 'ifs'
36 ofs=>'|', # the same as 'output_field_sep'
37 ofn=>'out.dat', # the same as 'output_file_name'
38 odf=>'out.def', # the same as 'output_def_file'
39 );
40 $dsp = Data::Describe->new(%arg); # with arguments
41  
42 $dsp->skip_first_row; # i,e. 1st row contains col names
43 $dsp->set_sfr(1); # is the same as the above
44  
45 $dsp->set_ifs('\t'); # set input field separator to tab
46 $dsp->input_field_separator('|'); # set input field separator to '|'
47 $dsp->set_ofs('|'); # set output field separator to |
48 $dsp->output_field_separator('|');# set output field separator to |
49  
50 $dsp->set_ifn('input.txt'); # set input file name
51 $dsp->input_file_name('input.txt'); # set input file name
52 $dsp->input_file_name($arf); # it can be array ref
53  
54 $dsp->set_ofn('out.dat'); # set output file name
55 $dsp->output_file_name('out.dat');# set output file name
56 $dsp->output_file_name('Y'); # it can be array ref
57  
58 $dsp->set_odf('out.def'); # set output def file name
59 $dsp->output_def_file('output.def');# set output definition file name
60 $dsp->output_def_file('Y'); # default to '${in}.def"
61  
62 # all the set method has its corresponding get method
63 $rc = $dsp->get_sfr;
64 $rc = $dsp->get_ifs;
65 $rc = $dsp->input_field_separator; # the same as get_ifs
66  
67 $dsp->debug(5); # set debug level to 5
68 $dsp->echoMSG('This message', 1); # tag the message as level 1
69 my $crf = $dsp->get_def_arrayref;
70 my $drf = $dsp->get_dat_arrayref;
71 $dsp->output($crf, "", 'def'); # output def file to STDOUT
72 $dsp->outptu($drf, 'out.dat', 'dat');
73  
74 =head1 DESCRIPTION
75  
76 This class contains a describe method that scans through each records
77 or number of records sepcified and fields in those records in the
78 array or a file to collect information about the content in the
79 array or the file. It creates a column definition array and a data
80 array containing all the data without the column record.
81  
82 The column definition array built by the module is actually an array
83 with hash members. It contains these hash elements ('col', 'typ',
84 'max', 'min', 'dec', 'req' and 'dsp') for each column. The subscripts
85 in the array are in the format of $ary[$col_seq]{$hash_ele}. The hash
86 elements are:
87  
88 col - column name
89 typ - column type, 'N' for numeric, 'C' for characters,
90 and 'D' for date
91 max - maximum length of the records in the column
92 (could use 'wid' to record the max length of the
93 records.)
94 min - minimum length of the record in the column
95 (When 'wid' is used, no 'min' is needed.)
96 dft - date format such as YYYY/MM/DD, MON/DD/YYYY, etc.
97 dec - maximun decimal length of the record in the column
98 req - whether there is null or zero length records in the
99 column only 'NOT NULL is shown
100 dsp - description of the columns
101  
102 The array or records passed to the module can have the first row
103 containing column names.
104  
105 =cut
106  
107 # bootstrap Data::Describe $VERSION;
108  
109 { # Encapsulated class data
110 my %_attr_data = # default accessibility
111 ( # method => ['type', 'access', 'default value']
112 # method type: $ - scalar method
113 # % - array ref method
114 # method access: R - read access
115 # W - write access
116 # method default: undef - undefined initially, but r
117 # equired at runtime
118 _ifn => ['$','R/W',undef], # input file name
119 _sfr => ['$','R/W',1], # skip first row: yes
120 _ifs => ['$','R/W','|'], # input field separator
121 _ofs => ['$','R/W','|'], # output field separator
122 _ofn => ['$','R/W',''], # output file name
123 _odf => ['$','R/W',''], # output def file name
124 _def_arrayref => ['$','R',''], # column def array ref
125 _dat_arrayref => ['$','R',''], # data array ref
126 );
127 # class methods, to operate on encapsulated class data
128 # is a specified object attribute accessible in a given mode
129 sub _accessible {
130 my ($self, $attr, $mode) = @_;
131 my $c = substr($mode, 0, 1);
132 my $m = $_attr_data{$attr}[1]; $m =~ s /\//\|/g;
133 # print "$mode, $c, $m\n";
134 return $c =~ /($m)/i if exists $_attr_data{$attr};
135 }
136 # classwide default value for a specified object attributes
137 sub _default_for {
138 my ($self, $attr) = @_;
139 return $_attr_data{$attr}[2] if exists $_attr_data{$attr};
140 }
141 sub _accs_type {
142 my ($self, $attr) = @_;
143 return $_attr_data{$attr}[0] if exists $_attr_data{$attr};
144 }
145 # list of names of all specified object attributes
146 sub _standard_keys { keys %_attr_data; }
147 }
148  
149 =head1 METHODS
150  
151 This class contains many methods to "set" and/or "get" parameters.
152 Here is the list of methods:
153  
154 =over 4
155  
156 =item * the constructor new(%arg)
157  
158 Without any input, i.e., new(), the constructor generates an empty
159 object. If any argument is provided, the constructor expects them in
160 the right order.
161  
162 =back
163  
164 =cut
165  
166 sub new {
167 my $caller = shift;
168 my $caller_is_obj = ref($caller);
169 my $class = $caller_is_obj || $caller;
170 my $self = bless {}, $class;
171 my %arg = @_; # convert rest of inputs into hash array
172 # populate the references to hash or even overwrite them
173 # if they are defined in the input hash
174 foreach my $attrname ( $self->_standard_keys() ) {
175 my ($argname) = ($attrname =~ /^_(.*)/);
176 if (exists $arg{$argname}) {
177 $self->{$attrname} = $arg{$argname};
178 } elsif ($caller_is_obj) {
179 $self->{$attrname} = $caller->{$attrname};
180 } else {
181 $self->{$attrname} = $self->_default_for($attrname);
182 }
183 }
184 my $als='input_file_name,input_field_sep,input_field_separator';
185 $als .= ',output_field_sep,output_field_separator,';
186 $als .= 'output_def_file,output_definition_file,set_dfn,';
187 $als .= 'definition_file_name,skip_first_row,debug';
188 foreach my $a ( split /,/, $als ) {
189 if (exists $arg{$a} && $self->can($a)) {
190 $self->$a($arg{$a});
191 }
192 }
193
194 # my $i = "";
195 # foreach $i (sort keys %arg) { print "$i=$arg{$i}\n"; }
196 # foreach $i (sort keys %{$self}) { print "$i=${$self}{$i}\n"; }
197 return $self;
198 }
199  
200 # destructor adjusts class count
201 sub DESTROY {
202 my ($self) = @_;
203 # clean up base classes
204 return if !@ISA;
205 foreach my $parent (@ISA) {
206 next if $self::DESTROY{$parent}++;
207 my $destructor = $parent->can("DESTROY");
208 $self->$destructor() if $destructor;
209 }
210 }
211  
212 =over 4
213  
214 =item * [set|get]_sfr/skip_first_row(1)
215  
216 This method tells whether the first row in the array or a file
217 containing column names. If it is true, the describe method will skip
218 it. The get method allows you to query current condition.
219 The default is false.
220  
221 =back
222  
223 =cut
224  
225 sub skip_first_row {
226 my $s = shift;
227 croak "ERR: Too many args to input_file_name." if @_ > 1;
228 @_ ? ($s->{_sfr}=shift) : return $s->{_sfr};
229 }
230  
231 =over 4
232  
233 =item * [set|get]_ifs/input_field_sep/input_field_separator
234  
235 This method sets/gets input field separator. The default separator is
236 vertical bar ('|').
237  
238 =back
239  
240 =cut
241  
242 sub input_field_sep {
243 my $s = shift;
244 croak "ERR: Too many args to input_file_name." if @_ > 1;
245 @_ ? ($s->{_ifs}=shift) : return $s->{_ifs};
246 }
247  
248 sub input_field_separator {
249 my $s = shift;
250 croak "ERR: Too many args to input_file_name." if @_ > 1;
251 @_ ? ($s->{_ifs}=shift) : return $s->{_ifs};
252 }
253  
254 =over 4
255  
256 =item * [set|get]_ofs/output_field_sep/output_field_separator
257  
258 This method sets/gets output field separator. The default separator
259 is a vertical bar ('|').
260  
261 =back
262  
263 =cut
264  
265 sub output_field_sep {
266 my $s = shift;
267 croak "ERR: Too many args to input_file_name." if @_ > 1;
268 @_ ? ($s->{_ofs}=shift) : return $s->{_ofs};
269 }
270  
271 sub output_field_separator {
272 my $s = shift;
273 croak "ERR: Too many args to input_file_name." if @_ > 1;
274 @_ ? ($s->{_ofs}=shift) : return $s->{_ofs};
275 }
276  
277 =over 4
278  
279 =item * [set|get]_ifn/input_file_name
280  
281 This method sets/gets input file name. It can also be an array
282 reference to a two-dimension array.
283 If it contains an array ref, an array will be scanned and described
284 instead of a text file.
285  
286 =back
287  
288 =cut
289
290 sub input_file_name {
291 my $s = shift;
292 croak "ERR: Too many args to input_file_name." if @_ > 1;
293 @_ ? ($s->{_ifn}=shift) : return $s->{_ifn};
294 }
295  
296 =over 4
297  
298 =item * [set|get]_ofn/output_file_name
299  
300 This method sets/gets output file file name. It defaults to undef.
301 It can be a 'Y', then the output file name will be defaulted to
302 'dsbf.dat' or the same as input file name with extension as '.dat'.
303  
304 =back
305  
306 =cut
307
308 sub output_file_name {
309 my $s = shift;
310 croak "ERR: Too many args to input_file_name." if @_ > 1;
311 @_ ? ($s->{_ofn}=shift) : return $s->{_ofn};
312 }
313  
314 =over 4
315  
316 =item * [set|get]_odf/output_def_file
317  
318 This method sets/gets output file name for column definition.
319 It defaults to undef. It can be 'Y', then the file name will be
320 defaulted to the same as input file name with extension as '.def';
321 if the input is an array, then it defaults to 'dsbf.def'.
322  
323 =back
324  
325 =cut
326
327 sub output_def_file {
328 my $s = shift;
329 croak "ERR: Too many args to input_file_name." if @_ > 1;
330 @_ ? ($s->{_odf}=shift) : return $s->{_odf};
331 }
332  
333 sub output_definition_file {
334 my $s = shift; return $s->output_def_file(@_);
335 }
336  
337 sub definition_file_name {
338 my $s = shift; return $s->output_def_file(@_);
339 }
340  
341 sub set_dfn {
342 my $s = shift; return $s->output_def_file(@_);
343 }
344  
345 sub get_dfn {
346 my $s = shift; return $s->output_def_file(@_);
347 }
348  
349 =over 4
350  
351 =item * get_def_arrayref
352  
353 This method gets the reference pointing to the column definition array.
354 The column definition array contains column name, column type,
355 column max length, column min length, column decimal length, and
356 column constraints.
357  
358 =item * get_dat_arrayref
359  
360 This method gets data array reference.
361 It does not change the internal attributes defined for
362 the object, so you can pass any data array reference to this method
363 without touching the internal attributes in the object. Actually, all
364 the I<get> methods do not change anything in the object.
365  
366 =back
367  
368 =cut
369  
370 # implement other get_... and set_... method (create as neccessary)
371 sub AUTOLOAD {
372 no strict "refs";
373 my ($self, $v1, $v2) = @_;
374 (my $sub = $AUTOLOAD) =~ s/.*:://;
375 my $m = $sub;
376 (my $attr = $sub) =~ s/^(get|set)//;
377 $attr = "$attr";
378 # print join "|", $self, $v1, $v2, $sub, $attr,"\n";
379 my $type = $self->_accs_type($attr);
380 croak "ERR: No such method: $AUTOLOAD.\n" if !$type;
381 my $v = "";
382 my $msg = "WARN: no permission to change";
383 if ($type eq '$') { # scalar method
384 $v = "\n";
385 $v .= " my \$s = shift;\n";
386 $v .= " croak \"ERR: Too many args to $m.\" if \@_ > 1;\n";
387 if ($self->_accessible($attr, 'write')) {
388 $v .= " \@_ ? (\$s->{$attr}=shift) : ";
389 $v .= "return \$s->{$attr};\n";
390 } else {
391 $v .= " \@_ ? (carp \"$msg $m.\n\") : ";
392 $v .= "return \$s->{$attr};\n";
393 }
394 } elsif ($type eq '@') { # array method
395 $v = "\n";
396 $v .= " my \$s = shift;\n";
397 $v .= " my \$a = \$s->{$attr}; # get array ref\n";
398 $v .= " if (\@_ && (ref(\$_[0]) eq 'ARRAY' ";
399 $v .= "|| \$_[0] =~ /.*=ARRAY/)) {\n";
400 $v .= " \$s->{$attr} = shift; return;\n }\n";
401 $v .= " my \$i; # array index\n";
402 $v .= " \@_ ? (\$i=shift) : return \$a;\n";
403 $v .= " croak \"ERR: Too many args to $m.\" if \@_ > 1;\n";
404 if ($self->_accessible($attr, 'write')) {
405 $v .= " \@_ ? (\${\$a}[\$i]=shift) : ";
406 $v .= "return \${\$a}[\$i];\n";
407 } else {
408 $v .= " \@_ ? (carp \"$msg $m.\n\") : ";
409 $v .= "return \${\$a}[\$i];\n";
410 }
411 } else { # assume hash method: type = '%'
412 $v = "\n";
413 $v .= " my \$s = shift;\n";
414 $v .= " my \$a = \$s->{$attr}; # get hash array ref\n";
415 $v .= " if (\@_ && (ref(\$_[0]) eq 'HASH' ";
416 $v .= " || \$_[0] =~ /.*=HASH/)) {\n";
417 $v .= " \$s->{$attr} = shift; return;\n }\n";
418 $v .= " my \$k; # hash array key\n";
419 $v .= " \@_ ? (\$k=shift) : return \$a;\n";
420 $v .= " croak \"ERR: Too many args to $m.\" if \@_ > 1;\n";
421 if ($self->_accessible($attr, 'write')) {
422 $v .= " \@_ ? (\${\$a}{\$k}=shift) : ";
423 $v .= "return \${\$a}{\$k};\n";
424 } else {
425 $v .= " \@_ ? (carp \"$msg $m.\n\") : ";
426 $v .= "return \${\$a}{\$k};\n";
427 }
428 }
429 $self->echoMSG("sub $m {$v}\n",100);
430 *{$sub} = eval "sub {$v}";
431 goto &$sub;
432 }
433  
434 =over 4
435  
436 =item * describe($inf,$def,$out,$sfr,$ifs,$ofs,$nrc,$owt,$chr)
437  
438 =over 8
439  
440 =item * Input variables:
441  
442 $inf - input file name, full path to a ASCII file
443 $def - output file name for column definitions,
444 default to "*.def" while $def = undef or 'Y'
445 $out - output file name for data,
446 default to "*.dat" while $out = 'Y'
447 $sfr - skip first row, i.e., the first row contains
448 column names
449 $ifs - input field separator, default is '|'
450 $ofs - output field separator, default is '|'
451 $nrc - first number of lines to be read,
452 default is to read all
453 $owt - overwrite existing files, default to 'N'
454 $chr - quote characters to be removed.
455  
456 =item * Variables used or routines called:
457  
458 echoMSG - print debug messages
459  
460 =item * How to use:
461  
462 use Data::Describe;
463 my $dsb= Data::Describe->new;
464 my ($crf,$drf) = $dsp->describe($inf,'Y','',$sfr);
465  
466 =item * Return: none.
467  
468 You can get the output through method I<get_def_arrayref> and
469 I<get_dat_arrayref>, or specify output file names and call
470 I<output> method.
471  
472 =back
473  
474 This routine reads in a text file, search its content and create
475 column definitons. The $crf contains the column definiton, i.e.,
476 ${$crf}[$j]{$itm}, where $j is column sequence and $itm includes:
477 'col', 'typ', 'wid', 'dec', 'dft', 'dsp', etc.
478  
479 The $drf contains the data, ${$drf}[$i][$j], where $i is record
480 number and $j is column name. The first row contains
481 column names. The rest rows are data.
482  
483 =back
484  
485 =cut
486  
487 sub describe {
488 my $self = shift;
489 my ($inf,$def,$out,$sfr,$ifs,$ofs,$nrc,$owt,$chr) = @_;
490 $inf = $self->get_ifn if !$inf;
491 croak "ERR: no input file/array is specified.\n" if !$inf;
492 $self->echoMSG(" - describing $inf...");
493 $sfr = $self->get_sfr if !$sfr;
494 $sfr = 'N' if !$sfr; # default skip first row to 'N'
495 $ifs = $self->get_ifs if !$ifs;
496 $ifs = '\|' if !$ifs; # default input field sep to '|'
497 $ofs = $self->get_ofs if !$ofs;
498 $ofs = '\|' if !$ofs; # default output field sep to '|'
499 $nrc = 0 if !$nrc; # default sample records to 0 (all)
500 # $dfs = '/' if !$dfs; # default dir separator to '/'
501 $owt = 'N' if !$owt; # default overwrite to 'N'
502 $chr = '"' if !$chr; # default quote character to '"'
503 my ($fhi, @data);
504 if ($inf =~ /ARRAY/) {
505 @data = @{$inf};
506 } else {
507 croak "ERR: input file does not exist.\n" if (!-f $inf);
508 $fhi = new IO::File "<$inf"; # input file handler
509 croak "ERR: could not open file - $inf.\n" if (!defined($fhi));
510 @data = <$fhi>;
511 undef $fhi;
512 }
513 #
514 # read the data and process it
515 my(@a, @b, $j, $n, $c, $v, $msg);
516 my @A=(); # store field definition information
517 my @D=(); # store possible date field information
518 my $max_nf = 0; # max number of fields
519 my $i = -1;
520 my $drf = bless [], ref($self)||$self;
521 foreach (@data) {
522 # skip empty and comment lines
523 next if (!$_ || $_ =~ /^\s+$/ || $_ =~ /^#/);
524 ++$i; chomp;
525 @a = split /$ifs/, $_, 99999;
526 $max_nf = ($#a+1>$max_nf)? $#a+1 : $max_nf;
527 if ($chr) {
528 for $j (0..$#a) { next if !$a[$j];
529 $a[$j] =~ s/^\s*//; # remove leading spaces
530 $a[$j] =~ s/\s*$//; # remove trailing spaces
531 $a[$j] =~ s/^($chr)*//; # remove leading quote char
532 $a[$j] =~ s/($chr)*?$//; # remove trailing quote char
533 }
534 }
535 if ($i==0) { # define column names
536 if ($sfr =~ /^Y$/i || $sfr == 1) {
537 # get column names from the first row
538 for $j (0..$#a) {
539 if (!$a[$j] || $a[$j] =~ /^\s*$/) {
540 $A[$j]{'col'} = sprintf "FLD%03d", $j+1;
541 } else {
542 $A[$j]{'col'} = $a[$j];
543 }
544 }
545 next; # skip the first column
546 } else { # generate seq column names
547 for $j (0..$#a) {
548 $A[$j]{'col'} = sprintf "FLD%03d", $j+1;
549 }
550 }
551 for $j (0..$#A) {
552 ${$drf}[0][$j] = $A[$j]{col};
553 }
554 }
555 push(@{$drf}, [@a]);
556 for $j (0..$#a) { # loop thru fields
557 $v = $a[$j]; # value in the field
558 if (!defined($A[$j]{'max'})) { $A[$j]{'max'} = -1; }
559 if (!defined($A[$j]{'min'})) { $A[$j]{'min'} = 9999999; }
560 if (!defined($A[$j]{'typ'})) { $A[$j]{'typ'} = ""; }
561 if (!defined($A[$j]{'dft'})) { $A[$j]{'dft'} = ""; }
562 if (!defined($A[$j]{'dsp'})) { $A[$j]{'dft'} = ""; }
563 if (!defined($A[$j]{'dec'})) { $A[$j]{'dec'} = 0; }
564 if ($A[$j]{'max'}<length($v)){ $A[$j]{'max'}=length($v); }
565 if ($A[$j]{'min'}>length($v)){ $A[$j]{'min'}=length($v); }
566 if (!$A[$j]{'typ'} || $A[$j]{'typ'} ne 'C') {
567 if ($v =~ /^-?[\d\.]*$/) { # it is numerical
568 $A[$j]{'typ'} = 'N';
569 } elsif ($v =~ /^[\d \/\.]*$/ ) { # it is date?
570 $A[$j]{'typ'} = 'D';
571 @b = split /\//, $v;
572 # first date field
573 if (!defined($D[$j][1]{min})) {
574 $D[$j][1]{min} = 999999;
575 }
576 # if (!exists $D[$j][1]{min}) {
577 # $D[$j][1]{min} = 999999;
578 # }
579 if (!defined($D[$j][1]{max})) {
580 # if (!exists $D[$j][1]{max}) {
581 $D[$j][1]{max} = -1;
582 }
583 $D[$j][1]{min} = ($D[$j][1]{min}>$b[0]) ? $b[0] :
584 $D[$j][1]{min};
585 $D[$j][1]{max} = ($D[$j][1]{max}<$b[0]) ? $b[0] :
586 $D[$j][1]{max};
587 # second date field
588 if (!exists $D[$j][2]{min}) {
589
590 $D[$j][2]{min} = 999999;
591 }
592 if (!exists $D[$j][2]{max}) {
593 $D[$j][2]{max} = -1;
594 }
595 $D[$j][2]{min} = ($D[$j][2]{min}>$b[0]) ? $b[1] :
596 $D[$j][2]{min};
597 $D[$j][2]{max} = ($D[$j][2]{max}<$b[0]) ? $b[1] :
598 $D[$j][2]{max};
599 # third date field
600 if (!exists $D[$j][3]{min}) {
601 $D[$j][3]{min} = 999999;
602 }
603 if (!exists $D[$j][3]{max}) {
604 $D[$j][3]{max} = -1;
605 }
606 $D[$j][3]{min} = ($D[$j][3]{min}>$b[0]) ? $b[2] :
607 $D[$j][3]{min};
608 $D[$j][3]{max} = ($D[$j][3]{max}<$b[0]) ? $b[2] :
609 $D[$j][3]{max};
610 } else {
611 $A[$j]{'typ'} = 'C';
612 }
613 }
614 if ($A[$j]{'typ'} eq 'N') { # it is numeric
615 if (!defined($A[$j]{'dec'})) { $A[$j]{'dec'} = 0; }
616 @b = split /\./, $v;
617 if (!defined($b[1])) { $b[1] = ""; } # so no warning
618 if ($A[$j]{'dec'}<length($b[1])) { # max decimal
619 $A[$j]{'dec'} = length($b[1]); # length
620 }
621 }
622 } # end of for $j (...)
623 } # end of while(<$fhi>)
624 my $tot = $i; if ($sfr !~ /^Y$/i) { $tot = $i+1; }
625 my $tcn = $#A+1;
626 my ($mx1, $mx2, $mx3, $mn1, $mn2, $mn3);
627 for $i (0..$#A) {
628 if ($A[$i]{'min'}>0) { $A[$i]{'req'} = 'NOT NULL';
629 } else { $A[$i]{'req'} = "" }
630 $A[$i]{'col'} =~ s/^\s*//; # trim leading spaces
631 $A[$i]{'col'} =~ s/\s*$//; # trim ending spaces
632 $A[$i]{'dsp'} = $A[$i]{'col'};
633 $A[$i]{'col'} =~ s/[ \/]/_/ig; # convert space and / to _
634 # determine date format
635 if ($A[$i]{typ} =~ /^D/i) {
636 $mn1 = $D[$i][1]{min}; $mx1 = $D[$i][1]{max};
637 $mn2 = $D[$i][2]{min}; $mx2 = $D[$i][2]{max};
638 $mn3 = $D[$i][3]{min}; $mx3 = $D[$i][3]{max};
639 $A[$i]{dft} = $self->get_date_format("$mn1:$mx1",
640 "$mn2:$mx2", "$mn3:$mx3");
641 }
642 }
643 for $j (0..$max_nf) {
644 next if ($A[$j]{'col'});
645 if (!$A[$j]{'typ'}) { splice(@A, $j, 1); next; }
646 $A[$j]{'col'} = sprintf "FLD%03d", $j+1;
647 }
648 $self->{_def_arrayref} = \@A;
649 $self->{_dat_arrayref} = $drf;
650 $self->echoMSG(" Total records processed: $tot",2);
651 $self->echoMSG(" Total columns created: $tcn",2);
652 }
653  
654 =over 4
655  
656 =item * output($arf,$out,$otp,$ifn,$ofs,$owt)
657  
658 =over 8
659  
660 =item * Input variables:
661  
662 $arf - array ref
663 $out - output file name
664 $otp - output type: data or definition
665 $ifn - input file name as name reference
666 $ofs - output field separator
667 $owr - whether to overwrite existing file
668  
669 =item * Variables used or routines called:
670  
671 get_def_arrayref - get column definition array reference
672 get_dat_arrayref - get data array reference
673 get_odf - get definition output file name
674 get_ofn - get data output file name
675 get_ofs - get output field separator
676 get_ifn - get input file name
677 fileparse - parse file name
678  
679 =item * How to use:
680  
681 my $crf = $self->get_def_arrayref;
682 # output $crf to standard output device - STDOUT
683 $self->output($crf, "", 'def');
684 my $drf = $self->get_dat_arrayref;
685 # output $drf to 'out.dat'
686 $self->output($drf, "out.dat", 'dat');
687  
688 =item * Return: None.
689  
690 =back
691  
692 =back
693  
694 =cut
695  
696 sub output {
697 my $self = shift;
698 my ($arf, $out, $otp, $ifn, $ofs, $owt) = @_;
699 # Input variables:
700 # $arf - array ref
701 # $out - output file name
702 # $otp - output type: data or definition
703 # $ifn - input file name as name reference
704 # $ofs - output field separator
705 # $owr - whether to overwrite existing file
706 #
707 $self->echoMSG('WARN: nothing to be outputed') if (!$arf && !$otp);
708 $otp = 'def' if !$otp;
709 if ($otp =~ /^def/i) { # column definition array ref
710 $arf = $self->get_def_arrayref if !$arf;
711 $out = $self->get_odf if !$out;
712 } else {
713 $arf = $self->get_dat_arrayref if !$arf;
714 $out = $self->get_ofn if !$out;
715 }
716 $self->echoMSG('WARN: no input array defined') if !$arf;
717 return if !$arf;
718 $owt = 'N' if !$owt;
719 $ofs = $self->get_ofs if !$ofs;
720 #
721 # let's determine output file name
722 $ifn = $self->get_ifn if !$ifn;
723 my $ds = '/';
724 $ifn = 'dsbf.dat' if !$ifn;
725 my ($bnm,$dir,$type)=fileparse($ifn,'\.\w+$');
726 my $fho = "";
727 if (!$out) {
728 $fho = *STDOUT;
729 } elsif ($out =~ /^Y/i) {
730 if ($otp =~ /^def/i) {
731 $out = "$dir${bnm}.def";
732 } else {
733 $out = "$dir${bnm}.dat";
734 }
735 $self->echoMSG(" - outputing to $out...");
736 if ($owt eq 'Y' && $out && -f $out) { unlink $out; }
737 carp "WARN: file - $out exist.\n" if -f $out;
738 $fho = new IO::File ">$out"; # output file hanlder
739 croak "ERR: could not write to $out.\n" if (!defined($fho));
740 }
741  
742 if ($otp =~ /^def/i) {
743 # ColName|ColType|ColWidth|ColRequirement|DateFmt|ColLabel
744 my ($t1, $t2, $t3);
745 $t1 = "# Input file name: $ifn\n" if $ifn;
746 $t1 = "# Input file name: $arf\n" if !$ifn;
747 $t1 .= "# Output file name: $out\n";
748 $t1 .= "# Created at " . (scalar localtime) . "\n";
749 $t1 .= "# Created by Data::Describe::output\n#";
750 $t2 = "# ColName|ColType|ColWidth|ColRequirement|DateFmt|";
751 $t2 .= "ColLabel";
752 my ($rec,$wid,$dsp,$typ);
753 print $fho "$t1\n$t2\n";
754 for my $i (0..$#{$arf}) {
755 $wid = 0; $typ = ${$arf}[$i]{'typ'};
756 if (${$arf}[$i]{'wid'}) { $wid = ${$arf}[$i]{'wid'};
757 } else { $wid = ${$arf}[$i]{'max'}; }
758 if ($typ eq 'N') { $wid = "$wid.${$arf}[$i]{'dec'}"; }
759 if (!defined(${$arf}[$i]{'dsp'})) {
760 ${$arf}[$i]{'dsp'} = "";
761 } else { $dsp = ${$arf}[$i]{'dsp'}; }
762 $rec = join $ofs, ${$arf}[$i]{'col'},$typ,
763 $wid,${$arf}[$i]{'req'},${$arf}[$i]{'dft'}, $dsp;
764 print $fho "$rec\n";
765 }
766 } else {
767 foreach (@{$arf}) {
768 print $fho (join $ofs, @{$_}) . "\n";
769 }
770 }
771 undef $fho;
772 }
773  
774 =over 4
775  
776 =item * debug($n)
777  
778 =over 8
779  
780 =item * Input variables:
781  
782 $n - a number between 0 and 100. It specifies the
783 level of messages that you would like to
784 display. The higher the number, the more
785 detailed messages that you will get.
786  
787 =item * Variables used or routines called: None.
788  
789 =item * How to use:
790  
791 $self->debug(2); # set the message level to 2
792 print $self->debug; # print current message level
793  
794 =item * Return: the debug level or set the debug level.
795  
796 =back
797  
798 =back
799  
800 =cut
801  
802 sub debug {
803 # my ($c_pkg,$c_fn,$c_ln) = caller;
804 # my $s = ref($_[0])?shift:(bless {}, $c_pkg);
805 my $s = shift;
806 croak "ERR: Too many args to debug." if @_ > 1;
807 @_ ? ($s->{_debug}=shift) : return $s->{_debug};
808 }
809  
810 =over 4
811  
812 =item * echoMSG($msg, $lvl, $yn)
813  
814 =over 8
815  
816 =item * Input variables:
817  
818 $msg - the message to be displayed. No newline
819 is needed in the end of the message. It
820 will add the newline code at the end of
821 the message.
822 $lvl - the message level is assigned to the message.
823 If it is higher than the debug level, then
824 the message will not be displayed.
825 $yn - whether to return the message
826  
827 =item * Variables used or routines called:
828  
829 debug - get debug level.
830  
831 =item * How to use:
832  
833 # default msg level to 0
834 $self->echoMSG('This is a test");
835 # set the msg level to 2
836 $self->echoMSG('This is a test", 2);
837  
838 =item * Return: None.
839  
840 =back
841  
842 This method will display message or a hash array based on I<debug>
843 level. If I<debug> is set to '0', no message or array will be
844 displayed. If I<debug> is set to '2', it will only display the message
845 level ($lvl) is less than or equal to '2'. If you call this
846 method without providing a message level, the message level ($lvl) is
847 default to '0'. Of course, if no message is provided to the method,
848 it will be quietly returned.
849  
850 This is how you can call I<echoMSG>:
851  
852 my $df = Data::Describe->new;
853 $df->echoMSG("This is a test"); # default the msg to level 0
854 $df->echoMSG("This is a test",1); # assign the msg as level 1 msg
855 $df->echoMSG("Test again",2); # assign the msg as level 2 msg
856 $df->echoMSG($hrf,1); # assign $hrf as level 1 msg
857 $df->echoMSG($hrf,2); # assign $hrf as level 2 msg
858  
859 If I<debug> is set to '1', all the messages with default message levels
860 0 and 1 will be displayed. The higher level messages
861 will not be displayed.
862  
863 =back
864  
865 =cut
866  
867 sub echoMSG {
868 my $self = shift;
869 my ($msg,$lvl,$yn) = @_;
870 if (!defined($msg)) { return; } # return if no msg
871 if (!defined($lvl)) { $lvl = 0; } # default level to 0
872 return $msg if $yn;
873 my $class = ref($self)||$self; # get class name
874 my $dbg = $self->debug; # get debug level
875 if (!$dbg) { return; } # return if not debug
876 my $ref = ref($msg);
877 return if ($lvl > $dbg );
878 if ($ref eq $class) { # an array?
879 # $self->disp_param($msg);
880 } else { print "$msg\n"; }
881 }
882  
883 =over 4
884  
885 =item * get_date_format($r1, $r2, $r3, $ds)
886  
887 Input variables:
888  
889 $r1 - date range 1: 'min:max'
890 $r2 - date range 2: 'min:max'
891 $r3 - date range 3: 'min:max'
892 $ds - date separator
893  
894 Variables used or routines called:
895  
896 None.
897  
898 How to use:
899  
900 # the $dft = 'MM/DD/YY'
901 my $dft = $self->get_date_format('1:12','1:31','1:2');
902 # the $dft = 'MM/DD/YYYY'
903 $dft = $self->get_date_format('1:12','1:31','0:2002');
904  
905 Return: the date format.
906  
907 =back
908  
909 =cut
910  
911 sub get_date_format {
912 my $self = shift;
913 my ($r1, $r2, $r3, $ds) = @_;
914 # Input variables:
915 # $r1 - date range 1: 'min:max'
916 # $r2 - date range 2: 'min:max'
917 # $r3 - date range 3: 'min:max'
918 # $ds - date separator
919 #
920 my ($mn1, $mx1) = split /:/, $r1;
921 my ($mn2, $mx2) = split /:/, $r2;
922 my ($mn3, $mx3) = split /:/, $r3;
923 $ds = '/' if !$ds;
924 my ($msg, $dft, $d1, $d2, $d3) = ("", "", "", "", "");
925 if (($mn1>31 && $mx1<=99) || ($mn1>99 && $mx1<10000)) {
926 # 1st fd is YY or YYYY
927 if ($mn1>31 && $mx1<=99) { # 1st fd is YY
928 $d1 = 'YY';
929 } else { $d1 = 'YYYY'; } # 1st fd is YYYY
930 if ($mn2>=1 && $mx2<=12) { # 2nd fd is MM
931 $d2 = 'MM';
932 } elsif ($mn2>=1 && $mx2<=31) { # 2nd fd is DD
933 $d2 = 'DD';
934 }
935 if ($d1 eq 'MM' && $mn3>=1 && $mx3<=12) { # 3rd fd is DD
936 $d3 = 'DD';
937 } elsif ($mn3>=1 && $mx3<=12) { # 3rd fd is MM
938 $d3 = 'MM';
939 } elsif ($mn3>=1 && $mx3<=31) { # 3rd fd is DD
940 $d3 = 'DD';
941 }
942 } elsif ($mn1>=1 && $mx1<=12) { # 1st fd is MM
943 $d1 = 'MM';
944 if ($mx2>31 && $mx2<=99) { # 2nd fd is YY
945 $d2 = 'YY';
946 } elsif ($mx2>99 && $mx2<10000) { # 2nd fd is YYYY
947 $d2 = 'YY';
948 } elsif ($mn2>=1 && $mx2<=31) { # 2nd fd is DD
949 $d2 = 'DD';
950 }
951 if ($d2 eq 'DD' && $mx3<=99) { # 3nd fd is YY
952 $d3 = 'YY';
953 } elsif ($mn3>31 && $mx3<=99) { # 3nd fd is YY
954 $d3 = 'YY';
955 } elsif ($mn3>99 && $mx3<10000) { # 3nd fd is YYYY
956 $d3 = 'YYYY';
957 } elsif ($mn3>=1 && $mx3<=31) { # 3nd fd is DD
958 $d3 = 'DD';
959 }
960 } elsif ($mn1>=1 && $mx1<=31) { # 1st fd is DD
961 $d1 = 'DD';
962 if ($mx2>31 && $mx2<=99) { # 2nd fd is YY
963 $d2 = 'YY';
964 } elsif ($mx2>99 && $mx2<10000) { # 2nd fd is YYYY
965 $d2 = 'YY';
966 } elsif ($mn2>=1 && $mx2<=12) { # 2nd fd is MM
967 $d2 = 'MM';
968 }
969 if ($d2 eq 'MM' && $mx3<=99) { # 3nd fd is YY
970 $d3 = 'YY';
971 } elsif ($mx3>31 && $mx3<=99) { # 3nd fd is YY
972 $d3 = 'YY';
973 } elsif ($mx3>99 && $mx3<10000) { # 3nd fd is YYYY
974 $d3 = 'YYYY';
975 } elsif ($mn3>=1 && $mx3<=12) { # 3nd fd is MM
976 $d3 = 'MM';
977 }
978 } else { # 1st fd is YY (32~99)?
979 $d1 = 'YY';
980 if ($mn2>=1 && $mx2<=12) { # 2nd fd is MM
981 $d2 = 'MM';
982 } elsif ($mn2>=1 && $mx2<=31) { # 2nd fd is DD
983 $d2 = 'DD';
984 }
985 if ($d1 eq 'MM' && $mn3>=1 && $mx3<=12) { # 3rd fd is DD
986 $d3 = 'DD';
987 } elsif ($mn3>=1 && $mx3<=12) { # 3rd fd is MM
988 $d3 = 'MM';
989 } elsif ($mn3>=1 && $mx3<=31) { # 3rd fd is DD
990 $d3 = 'DD';
991 }
992 }
993 if ($d1 && $d2 && $d3 && ($d1 ne $d2) && ($d2 ne $d3)) {
994 $dft = join $ds, $d1, $d2, $d3;
995 } else {
996 $msg = "illegal date: $d1($r1), $d2($r2), $d3($r3)";
997 }
998 return ($dft) ? $dft : $msg;
999 }
1000  
1001 1; # ensure that the module can be successfully used.
1002  
1003 __END__