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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3