[Bio] / FigKernelPackages / Tracer.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.9 - (view) (download) (as text)

1 : olson 1.1 package Tracer;
2 :    
3 :     require Exporter;
4 :     @ISA = ('Exporter');
5 : parrello 1.6 @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert);
6 : parrello 1.9 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
7 : olson 1.1 use strict;
8 :     use Carp qw(longmess croak);
9 :     use CGI;
10 : parrello 1.7 use FIG_Config;
11 : parrello 1.9 use PageBuilder;
12 : olson 1.1
13 :     =head1 Tracing and Debugging Helpers
14 :    
15 :     =head2 Introduction
16 :    
17 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
18 :     L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace
19 : parrello 1.2 message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself
20 :     has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
21 : olson 1.1 level is less than or equal to this package's trace level and whose category is activated will
22 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
23 :     is less likely to be seen. A higher trace level passed to B<Setup> means more trace messages will
24 : olson 1.1 appear. To generate a trace message, use the following syntax.
25 :    
26 :     C<< Trace($message) if T(errors => 4); >>
27 :    
28 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
29 : parrello 1.3 category is active. Note that the special category C<main> is always active, so
30 : olson 1.1
31 : parrello 1.3 C<< Trace($message) if T(main => 4); >>
32 : olson 1.1
33 :     will trace if the trace level is 4 or more.
34 :    
35 :     If the category name is the same as the package name, all you need is the number. So, if the
36 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
37 :     active and the trace level is 2 or more.
38 :    
39 :     C<< Trace($message) if T(2); >>
40 :    
41 : parrello 1.2 To set up tracing, you call the C</Setup> method. The method takes as input a trace level, a list
42 : olson 1.1 of category names, and a set of options. The trace level and list of category names are
43 :     specified as a space-delimited string. Thus
44 :    
45 :     C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
46 :    
47 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
48 :     specifies that messages should be output as HTML paragraphs. The parameters are formatted
49 :     to make it easier to input tracing configuration on a web form.
50 : olson 1.1
51 :     In addition to HTML and file output for trace messages, you can specify that the trace messages
52 :     be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
53 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
54 :     the page output, they can be gathered together and displayed at the end of the page. This makes
55 :     it easier to debug page formatting problems.
56 :    
57 : parrello 1.4 Finally, you can specify that all trace messages be emitted as warnings.
58 :    
59 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
60 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
61 :     Thus, debugging information is available and easily retrieved even when the application is
62 :     being used out in the field.
63 :    
64 :     =cut
65 : parrello 1.2
66 : olson 1.1 # Declare the configuration variables.
67 :    
68 :     my $Destination = "NONE"; # Description of where to send the trace output.
69 : parrello 1.3 my %Categories = ( main => 1 );
70 : olson 1.1 # hash of active category names
71 :     my $TraceLevel = 0; # trace level; a higher trace level produces more
72 :     # messages
73 :     my @Queue = (); # queued list of trace messages.
74 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
75 : olson 1.1
76 :     =head2 Public Methods
77 :    
78 :     =head3 TSetup
79 :    
80 :     C<< TSetup($categoryList, $target); >>
81 :    
82 :     This method is used to specify the trace options. The options are stored as package data
83 :     and interrogated by the L</Trace> and L</T> methods.
84 :    
85 :     =over 4
86 :    
87 :     =item categoryList
88 :    
89 :     A string specifying the trace level and the categories to be traced, separated by spaces.
90 :     The trace level must come first.
91 :    
92 :     =item target
93 :    
94 :     The destination for the trace output. To send the trace output to a file, specify the file
95 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
96 :     to the file. Otherwise the file is cleared before tracing begins. In addition to sending
97 : parrello 1.9 the trace messages to a file, you can specify a special destination. C<HTML> will cause
98 : parrello 1.6 tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
99 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
100 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
101 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
102 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
103 : parrello 1.6 cause tracing to be suppressed.
104 : olson 1.1
105 :     =back
106 :    
107 :     =cut
108 :    
109 :     sub TSetup {
110 :     # Get the parameters.
111 :     my ($categoryList, $target) = @_;
112 :     # Parse the category list.
113 :     my @categoryData = split /\s+/, $categoryList;
114 :     # Extract the trace level.
115 :     $TraceLevel = shift @categoryData;
116 :     # Build the category hash.
117 :     for my $category (@categoryData) {
118 :     $Categories{$category} = 1;
119 :     }
120 :     # Now we need to process the destination information. The most important special
121 :     # case is the single ">", which requires we clear the file first. After doing
122 :     # so, we tack on another ">" sign so that future trace messages are appended.
123 :     if ($target =~ m/^>[^>]/) {
124 :     open TRACEFILE, $target;
125 :     print TRACEFILE Now() . " Tracing initialized.\n";
126 :     close TRACEFILE;
127 :     $Destination = ">$target";
128 :     } else {
129 :     $Destination = uc($target);
130 :     }
131 :     }
132 :    
133 : parrello 1.6 =head3 SetLevel
134 :    
135 :     C<< Tracer::SetLevel($newLevel); >>
136 :    
137 :     Modify the trace level. A higher trace level will cause more messages to appear.
138 :    
139 :     =over 4
140 :    
141 :     =item newLevel
142 :    
143 :     Proposed new trace level.
144 :    
145 :     =back
146 :    
147 :     =cut
148 :    
149 :     sub SetLevel {
150 :     $TraceLevel = $_[0];
151 :     }
152 :    
153 : olson 1.1 =head3 Now
154 :    
155 :     C<< my $string = Tracer::Now(); >>
156 :    
157 :     Return a displayable time stamp containing the local time.
158 :    
159 :     =cut
160 :    
161 :     sub Now {
162 :     my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
163 :     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
164 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
165 : parrello 1.2 return $retVal;
166 : olson 1.1 }
167 :    
168 :     # Pad a number to 2 digits.
169 :     sub _p2 {
170 :     my ($value) = @_;
171 :     $value = "0$value" if ($value < 10);
172 :     return $value;
173 :     }
174 :    
175 :     =head3 LogErrors
176 :    
177 :     C<< Tracer::LogErrors($fileName); >>
178 :    
179 :     Route the standard error output to a log file.
180 :    
181 :     =over 4
182 :    
183 :     =item fileName
184 :    
185 :     Name of the file to receive the error output.
186 :    
187 :     =back
188 :    
189 :     =cut
190 :    
191 :     sub LogErrors {
192 :     # Get the file name.
193 :     my ($fileName) = @_;
194 :     # Open the file as the standard error output.
195 :     open STDERR, '>', $fileName;
196 :     }
197 :    
198 : parrello 1.5 =head3 ReadOptions
199 :    
200 :     C<< my %options = Tracer::ReadOptions($fileName); >>
201 :    
202 :     Read a set of options from a file. Each option is encoded in a line of text that has the
203 :     format
204 :    
205 :     I<optionName>C<=>I<optionValue>C<; >I<comment>
206 :    
207 :     The option name must consist entirely of letters, digits, and the punctuation characters
208 : parrello 1.9 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
209 :     character is a semi-colon will be ignored. The return hash will map each option name to
210 : parrello 1.5 the corresponding option value.
211 :    
212 :     =over 4
213 :    
214 :     =item fileName
215 :    
216 :     Name of the file containing the option data.
217 :    
218 :     =item RETURN
219 :    
220 :     Returns a hash mapping the option names specified in the file to their corresponding option
221 :     value.
222 :    
223 :     =back
224 :    
225 :     =cut
226 :    
227 :     sub ReadOptions {
228 :     # Get the parameters.
229 :     my ($fileName) = @_;
230 :     # Open the file.
231 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
232 :     # Count the number of records read.
233 :     my ($records, $comments) = 0;
234 :     # Create the return hash.
235 :     my %retVal = ();
236 :     # Loop through the file, accumulating key-value pairs.
237 :     while (my $line = <CONFIGFILE>) {
238 :     # Denote we've read a line.
239 :     $records++;
240 :     # Determine the line type.
241 :     if ($line =~ /^\s*[\n\r]/) {
242 :     # A blank line is a comment.
243 :     $comments++;
244 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
245 :     # Here we have an option assignment.
246 :     retVal{$1} = $2;
247 :     } elsif ($line =~ /^\s*;/) {
248 :     # Here we have a text comment.
249 :     $comments++;
250 :     } else {
251 :     # Here we have an invalid line.
252 :     Trace("Invalid option statement in record $records.") if T(0);
253 :     }
254 :     }
255 :     # Return the hash created.
256 :     return %retVal;
257 :     }
258 :    
259 : olson 1.1 =head3 GetOptions
260 :    
261 :     C<< Tracer::GetOptions(\%defaults, \%options); >>
262 :    
263 :     Merge a specified set of options into a table of defaults. This method takes two hash references
264 :     as input and uses the data from the second to update the first. If the second does not exist,
265 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
266 :     exist in the first.
267 :    
268 :     Consider the following example.
269 :    
270 :     C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
271 :    
272 :     In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
273 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
274 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
275 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
276 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
277 :    
278 :     C<< {databaseType => 'Oracle'} >>
279 :    
280 :     an error will occur because the B<databaseType> option does not exist.
281 :    
282 :     =over 4
283 :    
284 :     =item defaults
285 :    
286 :     Table of default option values.
287 :    
288 :     =item options
289 :    
290 :     Table of overrides, if any.
291 :    
292 :     =item RETURN
293 :    
294 :     Returns a reference to the default table passed in as the first parameter.
295 :    
296 :     =back
297 :    
298 :     =cut
299 :    
300 :     sub GetOptions {
301 :     # Get the parameters.
302 :     my ($defaults, $options) = @_;
303 :     # Check for overrides.
304 :     if ($options) {
305 :     # Loop through the overrides.
306 :     while (my ($option, $setting) = each %{$options}) {
307 :     # Insure this override exists.
308 :     if (!exists $defaults->{$option}) {
309 :     croak "Unrecognized option $option encountered.";
310 :     } else {
311 :     # Apply the override.
312 :     $defaults->{$option} = $setting;
313 :     }
314 :     }
315 :     }
316 :     # Return the merged table.
317 :     return $defaults;
318 :     }
319 :    
320 :     =head3 MergeOptions
321 :    
322 :     C<< Tracer::MergeOptions(\%table, \%defaults); >>
323 :    
324 :     Merge default values into a hash table. This method looks at the key-value pairs in the
325 :     second (default) hash, and if a matching key is not found in the first hash, the default
326 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
327 :     checking and no return value.
328 :    
329 :     =over 4
330 :    
331 :     =item table
332 :    
333 :     Hash table to be updated with the default values.
334 :    
335 :     =item defaults
336 :    
337 :     Default values to be merged into the first hash table if they are not already present.
338 :    
339 :     =back
340 :    
341 :     =cut
342 :    
343 :     sub MergeOptions {
344 :     # Get the parameters.
345 :     my ($table, $defaults) = @_;
346 :     # Loop through the defaults.
347 :     while (my ($key, $value) = each %{$defaults}) {
348 :     if (!exists $table->{$key}) {
349 :     $table->{$key} = $value;
350 :     }
351 :     }
352 :     }
353 :    
354 :     =head3 Trace
355 :    
356 :     C<< Trace($message); >>
357 :    
358 :     Write a trace message to the target location specified in L</TSetup>. If there has not been
359 :     any prior call to B<TSetup>.
360 :    
361 :     =over 4
362 :    
363 :     =item message
364 :    
365 :     Message to write.
366 :    
367 :     =back
368 :    
369 :     =cut
370 :    
371 :     sub Trace {
372 :     # Get the parameters.
373 :     my ($message) = @_;
374 :     # Get the timestamp.
375 :     my $timeStamp = Now();
376 : parrello 1.9 # Format the message. Note we strip off any line terminators at the end.
377 :     my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
378 : olson 1.1 # Process according to the destination.
379 :     if ($Destination eq "TEXT") {
380 :     # Write the message to the standard output.
381 : parrello 1.5 print "$formatted\n";
382 :     } elsif ($Destination eq "ERROR") {
383 :     # Write the message to the error output.
384 :     print STDERR "$formatted\n";
385 : olson 1.1 } elsif ($Destination eq "QUEUE") {
386 :     # Push the message into the queue.
387 : parrello 1.5 push @Queue, "$formatted";
388 : olson 1.1 } elsif ($Destination eq "HTML") {
389 :     # Convert the message to HTML and write it to the standard output.
390 :     my $escapedMessage = CGI::escapeHTML($message);
391 : parrello 1.5 print "<p>$formatted</p>\n";
392 : parrello 1.4 } elsif ($Destination eq "WARN") {
393 :     # Emit the message as a warning.
394 :     warn $message;
395 : olson 1.1 } elsif ($Destination =~ m/^>>/) {
396 :     # Write the trace message to an output file.
397 :     open TRACING, $Destination;
398 : parrello 1.5 print TRACING "$formatted\n";
399 : olson 1.1 close TRACING;
400 :     }
401 :     }
402 :    
403 :     =head3 T
404 :    
405 : parrello 1.2 C<< my $switch = T($category, $traceLevel); >>
406 : olson 1.1
407 :     or
408 : parrello 1.2
409 : olson 1.1 C<< my $switch = T($traceLevel); >>
410 :    
411 :     Return TRUE if the trace level is at or above a specified value and the specified category
412 :     is active, else FALSE. If no category is specified, the caller's package name is used.
413 :    
414 :     =over 4
415 :    
416 :     =item category
417 :    
418 :     Category to which the message belongs. If not specified, the caller's package name is
419 :     used.
420 :    
421 :     =item traceLevel
422 :    
423 :     Relevant tracing level.
424 :    
425 :     =item RETURN
426 :    
427 :     TRUE if a message at the specified trace level would appear in the trace, else FALSE.
428 :    
429 :     =back
430 :    
431 :     =cut
432 :    
433 :     sub T {
434 :     # Declare the return variable.
435 :     my $retVal = 0;
436 :     # Only proceed if tracing is turned on.
437 :     if ($Destination ne "NONE") {
438 :     # Get the parameters.
439 :     my ($category, $traceLevel) = @_;
440 :     if (!defined $traceLevel) {
441 :     # Here we have no category, so we need to get the calling package.
442 :     $traceLevel = $category;
443 :     my ($package, $fileName, $line) = caller;
444 : parrello 1.3 # If there is no calling package, we default to "main".
445 : olson 1.1 if (!$package) {
446 : parrello 1.3 $category = "main";
447 : olson 1.1 } else {
448 :     $category = $package;
449 :     }
450 :     }
451 : parrello 1.7 # Save the category name.
452 :     $LastCategory = $category;
453 :     # Use the category and tracelevel to compute the result.
454 : olson 1.1 $retVal = ($traceLevel <= $TraceLevel && exists $Categories{$category});
455 : parrello 1.3 }
456 : olson 1.1 # Return the computed result.
457 : parrello 1.3 return $retVal;
458 : olson 1.1 }
459 :    
460 :     =head3 ParseCommand
461 :    
462 :     C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
463 :    
464 :     Parse a command line consisting of a list of parameters. The initial parameters may be option
465 : parrello 1.2 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
466 :     off and merged into a table of default options. The remainder of the command line is
467 : olson 1.1 returned as a list of positional arguments. For example, consider the following invocation.
468 :    
469 :     C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
470 :    
471 :     In this case, the list @words will be treated as a command line. There are two options available,
472 :     B<errors> and B<logFile>. If @words has the following format
473 :    
474 :     C<< -logFile=error.log apple orange rutabaga >>
475 :    
476 :     then at the end of the invocation, C<$options> will be
477 :    
478 :     C<< { errors => 0, logFile => 'error.log' } >>
479 :    
480 :     and C<@arguments> will contain
481 :    
482 :     C<< apple orange rutabaga >>
483 :    
484 : parrello 1.2 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
485 : olson 1.1 support for quote characters.
486 :    
487 :     =over 4
488 :    
489 :     =item optionTable
490 :    
491 :     Table of default options.
492 :    
493 :     =item inputList
494 :    
495 :     List of words on the command line.
496 :    
497 :     =item RETURN
498 :    
499 :     Returns a reference to the option table and a list of the positional arguments.
500 :    
501 :     =back
502 :    
503 :     =cut
504 :    
505 :     sub ParseCommand {
506 :     # Get the parameters.
507 :     my ($optionTable, @inputList) = @_;
508 :     # Process any options in the input list.
509 :     my %overrides = ();
510 :     while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
511 :     # Get the current option.
512 :     my $arg = shift @inputList;
513 :     # Pull out the option name.
514 :     $arg =~ /^-([^=]*)/g;
515 :     my $name = $1;
516 :     # Check for an option value.
517 :     if ($arg =~ /\G=(.*)$/g) {
518 :     # Here we have a value for the option.
519 :     $overrides{$name} = UnEscape($1);
520 :     } else {
521 :     # Here there is no value, so we use 1.
522 :     $overrides{$name} = 1;
523 :     }
524 :     }
525 :     # Merge the options into the defaults.
526 :     GetOptions($optionTable, \%overrides);
527 :     # Translate the remaining parameters.
528 :     my @retVal = ();
529 :     for my $inputParm (@inputList) {
530 :     push @retVal, UnEscape($inputParm);
531 :     }
532 :     # Return the results.
533 :     return ($optionTable, @retVal);
534 :     }
535 :    
536 : parrello 1.9 =head3 Escape
537 :    
538 :     C<< my $codedString = Tracer::Escape($realString); >>
539 :    
540 :     Escape a string for use in a command length. Spaces will be replaced by C<\b>,
541 :     tabs replaced by C<\t>, new-lines replaced by C<\n>, and backslashes will be
542 :     doubled. The effect is to exactly reverse the effect of L</UnEscape>.
543 :    
544 :     =over 4
545 :    
546 :     =item realString
547 :    
548 :     String to escape.
549 :    
550 :     =item RETURN
551 :    
552 :     Escaped equivalent of the real string.
553 :    
554 :     =back
555 :    
556 :     =cut
557 :    
558 :     sub Escape {
559 :     # Get the parameter.
560 :     my ($realString) = @_;
561 :     # Initialize the return variable.
562 :     my $retVal = "";
563 :     # Loop through the parameter string, looking for sequences to escape.
564 :     while (length $realString > 0) {
565 :     # Look for the first sequence to escape.
566 :     if ($realString =~ /^(.*?)([ \n\t\\])/) {
567 :     # Here we found it. The text preceding the sequence is in $1. The sequence
568 :     # itself is in $2. First, move the clear text to the return variable.
569 :     $retVal .= $1;
570 :     $realString = substr $realString, (length $2 + length $1);
571 :     # Encode the escape sequence.
572 :     my $char = $2;
573 :     $char =~ tr/ \t\n/btn/;
574 :     $retVal .= "\\" . $char;
575 :     } else {
576 :     # Here there are no more escape sequences. The rest of the string is
577 :     # transferred unmodified.
578 :     $retVal .= $realString;
579 :     $realString = "";
580 :     }
581 :     }
582 :     # Return the result.
583 :     return $retVal;
584 :     }
585 :    
586 : olson 1.1 =head3 UnEscape
587 :    
588 :     C<< my $realString = Tracer::UnEscape($codedString); >>
589 :    
590 :     Replace escape sequences with their actual equivalents. C<\b> will be replaced by a space,
591 :     C<\t> by a tab, C<\n> by a new-line character, and C<\\> by a back-slash.
592 :    
593 :     =over 4
594 :    
595 :     =item codedString
596 :    
597 :     String to un-escape.
598 :    
599 :     =item RETURN
600 :    
601 :     Returns a copy of the original string with the escape sequences converted to their actual
602 :     values.
603 :    
604 :     =back
605 :    
606 :     =cut
607 :    
608 :     sub UnEscape {
609 :     # Get the parameter.
610 :     my ($codedString) = @_;
611 :     # Initialize the return variable.
612 :     my $retVal = "";
613 : parrello 1.9 # Only proceed if the incoming string is nonempty.
614 :     if (defined $codedString) {
615 :     # Loop through the parameter string, looking for escape sequences. We can't do
616 :     # translating because it causes problems with the escaped slash. ("\\b" becomes
617 :     # "\ " no matter what we do.)
618 :     while (length $codedString > 0) {
619 :     # Look for the first escape sequence.
620 :     if ($codedString =~ /^(.*?)\\(\\|b|n|t)/) {
621 :     # Here we found it. The text preceding the sequence is in $1. The sequence
622 :     # itself is in $2. First, move the clear text to the return variable.
623 :     $retVal .= $1;
624 :     $codedString = substr $codedString, (2 + length $1);
625 :     # Decode the escape sequence.
626 :     my $char = $2;
627 :     $char =~ tr/\\btn/\\ \t\n/;
628 :     $retVal .= $char;
629 :     } else {
630 :     # Here there are no more escape sequences. The rest of the string is
631 :     # transferred unmodified.
632 :     $retVal .= $codedString;
633 :     $codedString = "";
634 :     }
635 : olson 1.1 }
636 :     }
637 :     # Return the result.
638 : parrello 1.2 return $retVal;
639 : olson 1.1 }
640 :    
641 :     =head3 ParseRecord
642 :    
643 :     C<< my @fields = Tracer::ParseRecord($line); >>
644 :    
645 :     Parse a tab-delimited data line. The data line is split into field values. Embedded tab
646 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
647 :     These will automatically be converted.
648 :    
649 :     =over 4
650 :    
651 :     =item line
652 :    
653 :     Line of data containing the tab-delimited fields.
654 :    
655 :     =item RETURN
656 :    
657 :     Returns a list of the fields found in the data line.
658 :    
659 :     =back
660 :    
661 :     =cut
662 :    
663 :     sub ParseRecord {
664 :     # Get the parameter.
665 :     my ($line) = @_;
666 :     # Remove the trailing new-line, if any.
667 :     chomp $line;
668 :     # Split the line read into pieces using the tab character.
669 :     my @retVal = split /\t/, $line;
670 :     # Trim and fix the escapes in each piece.
671 :     for my $value (@retVal) {
672 :     # Trim leading whitespace.
673 :     $value =~ s/^\s+//;
674 :     # Trim trailing whitespace.
675 :     $value =~ s/\s+$//;
676 :     # Delete the carriage returns.
677 :     $value =~ s/\r//g;
678 :     # Convert the escapes into their real values.
679 :     $value =~ s/\\t/"\t"/ge;
680 :     $value =~ s/\\n/"\n"/ge;
681 :     }
682 :     # Return the result.
683 :     return @retVal;
684 :     }
685 :    
686 :     =head3 Merge
687 :    
688 :     C<< my @mergedList = Tracer::Merge(@inputList); >>
689 :    
690 :     Sort a list of strings and remove duplicates.
691 :    
692 :     =over 4
693 :    
694 :     =item inputList
695 :    
696 :     List of scalars to sort and merge.
697 :    
698 :     =item RETURN
699 :    
700 :     Returns a list containing the same elements sorted in ascending order with duplicates
701 :     removed.
702 :    
703 :     =back
704 :    
705 :     =cut
706 :    
707 :     sub Merge {
708 :     # Get the input list in sort order.
709 :     my @inputList = sort @_;
710 :     # Only proceed if the list has at least two elements.
711 :     if (@inputList > 1) {
712 :     # Now we want to move through the list splicing out duplicates.
713 :     my $i = 0;
714 :     while ($i < @inputList) {
715 :     # Get the current entry.
716 :     my $thisEntry = $inputList[$i];
717 :     # Find out how many elements duplicate the current entry.
718 :     my $j = $i + 1;
719 :     my $dup1 = $i + 1;
720 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
721 :     # If the number is nonzero, splice out the duplicates found.
722 :     if ($j > $dup1) {
723 :     splice @inputList, $dup1, $j - $dup1;
724 :     }
725 :     # Now the element at position $dup1 is different from the element before it
726 :     # at position $i. We push $i forward one position and start again.
727 :     $i++;
728 :     }
729 :     }
730 :     # Return the merged list.
731 :     return @inputList;
732 :     }
733 :    
734 :     =head3 GetFile
735 :    
736 : parrello 1.6 C<< my @fileContents = Tracer::GetFile($fileName); >>
737 : olson 1.1
738 :     Return the entire contents of a file.
739 :    
740 :     =over 4
741 :    
742 :     =item fileName
743 :    
744 :     Name of the file to read.
745 :    
746 :     =item RETURN
747 :    
748 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
749 :     In a scalar context, returns the entire file as a string.
750 : olson 1.1
751 :     =back
752 :    
753 :     =cut
754 :    
755 :     sub GetFile {
756 :     # Get the parameters.
757 :     my ($fileName) = @_;
758 :     # Declare the return variable.
759 : parrello 1.6 my @retVal = ();
760 : olson 1.1 # Open the file for input.
761 :     my $ok = open INPUTFILE, "<$fileName";
762 :     if (!$ok) {
763 : parrello 1.6 # If we had an error, trace it. We will automatically return a null value.
764 :     Trace("Could not open \"$fileName\" for input.") if T(0);
765 : olson 1.1 } else {
766 : parrello 1.9 # Read the whole file into the return variable, stripping off any terminator
767 : parrello 1.6 # characters.
768 :     my $lineCount = 0;
769 :     while (my $line = <INPUTFILE>) {
770 :     $lineCount++;
771 : parrello 1.9 $line = Strip($line);
772 : parrello 1.6 push @retVal, $line;
773 : olson 1.1 }
774 :     # Close it.
775 :     close INPUTFILE;
776 : parrello 1.6 my $actualLines = @retVal;
777 : parrello 1.9 Trace("$lineCount lines read from $fileName. $actualLines processed.") if T(3);
778 : olson 1.1 }
779 : parrello 1.6 # Return the file's contents in the desired format.
780 : parrello 1.9 if (wantarray) {
781 : parrello 1.6 return @retVal;
782 :     } else {
783 :     return join "\n", @retVal;
784 :     }
785 : olson 1.1 }
786 :    
787 :     =head3 QTrace
788 :    
789 :     C<< my $data = QTrace($format); >>
790 :    
791 :     Return the queued trace data in the specified format.
792 :    
793 :     =over 4
794 :    
795 :     =item format
796 :    
797 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
798 :    
799 :     =back
800 :    
801 :     =cut
802 :    
803 :     sub QTrace {
804 :     # Get the parameter.
805 :     my ($format) = @_;
806 :     # Create the return variable.
807 :     my $retVal = "";
808 :     # Process according to the format.
809 :     if ($format =~ m/^HTML$/i) {
810 :     # Convert the queue into an HTML list.
811 :     $retVal = "<ul>\n";
812 :     for my $line (@Queue) {
813 :     my $escapedLine = CGI::escapeHTML($line);
814 :     $retVal .= "<li>$escapedLine</li>\n";
815 :     }
816 :     $retVal .= "</ul>\n";
817 :     } elsif ($format =~ m/^TEXT$/i) {
818 :     # Convert the queue into a list of text lines.
819 :     $retVal = join("\n", @Queue) . "\n";
820 :     }
821 :     # Clear the queue.
822 :     @Queue = ();
823 :     # Return the formatted list.
824 :     return $retVal;
825 :     }
826 :    
827 :     =head3 Confess
828 :    
829 :     C<< Confess($message); >>
830 :    
831 :     Trace the call stack and abort the program with the specified message. The stack
832 :     trace will only appear if the trace level for this package is 1 or more. When used with
833 : parrello 1.9 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
834 : parrello 1.6 So, for example
835 : olson 1.1
836 : parrello 1.6 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
837 : olson 1.1
838 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
839 :    
840 :     =over 4
841 :    
842 :     =item message
843 :    
844 :     Message to include in the trace.
845 :    
846 :     =back
847 :    
848 :     =cut
849 :    
850 :     sub Confess {
851 :     # Get the parameters.
852 :     my ($message) = @_;
853 :     # Trace the call stack.
854 :     Cluck($message) if T(1);
855 :     # Abort the program.
856 : parrello 1.5 croak(">>> $message");
857 : olson 1.1 }
858 :    
859 : parrello 1.6 =head3 Assert
860 :    
861 :     C<< Assert($condition1, $condition2, ... $conditionN); >>
862 :    
863 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
864 :     the OR operator and the L</Confess> method, B<Assert> can function as a debugging assert.
865 :     So, for example
866 :    
867 :     C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
868 :    
869 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
870 :    
871 :     =cut
872 :     sub Assert {
873 :     my $retVal = 1;
874 :     LOOP: for my $condition (@_) {
875 :     if (! $condition) {
876 :     $retVal = 0;
877 :     last LOOP;
878 :     }
879 :     }
880 :     return $retVal;
881 :     }
882 :    
883 : olson 1.1 =head3 Cluck
884 :    
885 :     C<< Cluck($message); >>
886 :    
887 :     Trace the call stack. Note that for best results, you should qualify the call with a
888 :     trace condition. For example,
889 :    
890 :     C<< Cluck("Starting record parse.") if T(3); >>
891 :    
892 :     will only trace the stack if the trace level for the package is 3 or more.
893 :    
894 :     =over 4
895 :    
896 :     =item message
897 :    
898 :     Message to include in the trace.
899 :    
900 :     =back
901 :    
902 :     =cut
903 :    
904 :     sub Cluck {
905 :     # Get the parameters.
906 :     my ($message) = @_;
907 : parrello 1.5 # Trace what's happening.
908 :     Trace("Stack trace for event: $message");
909 : olson 1.1 my $confession = longmess($message);
910 : parrello 1.5 # Convert the confession to a series of trace messages. Note we skip any
911 :     # messages relating to calls into Tracer.
912 : olson 1.1 for my $line (split /\s*\n/, $confession) {
913 : parrello 1.5 Trace($line) if ($line !~ /Tracer\.pm/);
914 : olson 1.1 }
915 :     }
916 :    
917 : parrello 1.5 =head3 Min
918 :    
919 :     C<< my $min = Min($value1, $value2, ... $valueN); >>
920 :    
921 :     Return the minimum argument. The arguments are treated as numbers.
922 :    
923 :     =over 4
924 :    
925 :     =item $value1, $value2, ... $valueN
926 :    
927 :     List of numbers to compare.
928 :    
929 :     =item RETURN
930 :    
931 :     Returns the lowest number in the list.
932 :    
933 :     =back
934 :    
935 :     =cut
936 :    
937 :     sub Min {
938 :     # Get the parameters. Note that we prime the return value with the first parameter.
939 :     my ($retVal, @values) = @_;
940 :     # Loop through the remaining parameters, looking for the lowest.
941 :     for my $value (@values) {
942 :     if ($value < $retVal) {
943 :     $retVal = $value;
944 :     }
945 :     }
946 :     # Return the minimum found.
947 :     return $retVal;
948 :     }
949 :    
950 :     =head3 Max
951 :    
952 :     C<< my $max = Max($value1, $value2, ... $valueN); >>
953 :    
954 :     Return the maximum argument. The arguments are treated as numbers.
955 :    
956 :     =over 4
957 :    
958 :     =item $value1, $value2, ... $valueN
959 :    
960 :     List of numbers to compare.
961 :    
962 :     =item RETURN
963 :    
964 :     Returns the highest number in the list.
965 :    
966 :     =back
967 :    
968 :     =cut
969 :    
970 :     sub Max {
971 :     # Get the parameters. Note that we prime the return value with the first parameter.
972 :     my ($retVal, @values) = @_;
973 :     # Loop through the remaining parameters, looking for the highest.
974 :     for my $value (@values) {
975 :     if ($value > $retVal) {
976 :     $retVal = $value;
977 :     }
978 :     }
979 :     # Return the maximum found.
980 :     return $retVal;
981 :     }
982 :    
983 :     =head3 AddToListMap
984 :    
985 :     C<< Tracer::AddToListMap(\%hash, $key, $value); >>
986 :    
987 :     Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
988 :     is created for the key. Otherwise, the new value is pushed onto the list.
989 :    
990 :     =over 4
991 :    
992 :     =item hash
993 :    
994 :     Reference to the target hash.
995 :    
996 :     =item key
997 :    
998 :     Key for which the value is to be added.
999 :    
1000 :     =item value
1001 :    
1002 :     Value to add to the key's value list.
1003 :    
1004 :     =back
1005 :    
1006 :     =cut
1007 :    
1008 :     sub AddToListMap {
1009 :     # Get the parameters.
1010 :     my ($hash, $key, $value) = @_;
1011 :     # Process according to whether or not the key already has a value.
1012 :     if (! exists $hash->{$key}) {
1013 :     $hash->{$key} = [$value];
1014 :     } else {
1015 :     push @{$hash->{$key}}, $value;
1016 :     }
1017 :     }
1018 : olson 1.1
1019 : parrello 1.7 =head3 DebugMode
1020 :    
1021 :     C<< if (Tracer::DebugMode) { ...code... } >>
1022 :    
1023 :     Return TRUE if debug mode has been turned on in FIG_Config, else output
1024 :     an error page and return FALSE.
1025 :    
1026 :     Certain CGI scripts are too dangerous to exist in the production
1027 :     environment. This method provides a simple way to prevent them
1028 :     from working unless they are explicitly turned on in the configuration
1029 :     file by setting C<$FIG_Config::debug_mode> to 1. If debugging mode
1030 :     is not turned on, an error web page will be output.
1031 :    
1032 :     =cut
1033 :    
1034 :     sub DebugMode {
1035 :     # Declare the return variable.
1036 :     my $retVal;
1037 :     # Check the debug configuration.
1038 :     if ($FIG_Config::debug_mode) {
1039 :     $retVal = 1;
1040 :     } else {
1041 :     # Here debug mode is off, so we generate an error page.
1042 : parrello 1.9 my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");
1043 :     print $pageString;
1044 :     }
1045 :     # Return the determination indicator.
1046 :     return $retVal;
1047 :     }
1048 :    
1049 :     =head3 Strip
1050 :    
1051 :     C<< my $string = Tracer::Strip($line); >>
1052 :    
1053 :     Strip all line terminators off a string. This is necessary when dealing with files
1054 :     that may have been transferred back and forth several times among different
1055 :     operating environments.
1056 :    
1057 :     =over 4
1058 :    
1059 :     =item line
1060 :    
1061 :     Line of text to be stripped.
1062 :    
1063 :     =item RETURN
1064 :    
1065 :     The same line of text with all the line-ending characters chopped from the end.
1066 :    
1067 :     =back
1068 :    
1069 :     =cut
1070 :    
1071 :     sub Strip {
1072 :     # Get a copy of the parameter string.
1073 :     my ($string) = @_;
1074 :     my $retVal = $string;
1075 :     # Strip the line terminator characters.
1076 :     $retVal =~ s/(\r|\n)+$//g;
1077 :     # Return the result.
1078 :     return $retVal;
1079 :     }
1080 :    
1081 :     =head3 Pad
1082 :    
1083 :     C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1084 :    
1085 :     Pad a string to a specified length. The pad character will be a
1086 :     space, and the padding will be on the right side unless specified
1087 :     in the third parameter.
1088 :    
1089 :     =over 4
1090 :    
1091 :     =item string
1092 :    
1093 :     String to be padded.
1094 :    
1095 :     =item len
1096 :    
1097 :     Desired length of the padded string.
1098 :    
1099 :     =item left (optional)
1100 :    
1101 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1102 :    
1103 :     =item padChar (optional)
1104 :    
1105 :     =item RETURN
1106 :    
1107 :     Returns a copy of the original string with the spaces added to the specified end so
1108 :     that it achieves the desired length.
1109 :    
1110 :     =back
1111 :    
1112 :     =cut
1113 :    
1114 :     sub Pad {
1115 :     # Get the parameters.
1116 :     my ($string, $len, $left, $padChar) = @_;
1117 :     # Compute the padding character.
1118 :     if (! defined $padChar) {
1119 :     $padChar = " ";
1120 :     }
1121 :     # Compute the number of spaces needed.
1122 :     my $needed = $len - length $string;
1123 :     # Copy the string into the return variable.
1124 :     my $retVal = $string;
1125 :     # Only proceed if padding is needed.
1126 :     if ($needed > 0) {
1127 :     # Create the pad string.
1128 :     my $pad = $padChar x $needed;
1129 :     # Affix it to the return value.
1130 :     if ($left) {
1131 :     $retVal = $pad . $retVal;
1132 :     } else {
1133 :     $retVal .= $pad;
1134 : redwards 1.8 }
1135 : parrello 1.7 }
1136 : parrello 1.9 # Return the result.
1137 : parrello 1.7 return $retVal;
1138 :     }
1139 :    
1140 : redwards 1.8 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3