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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3