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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : olson 1.30 #
2 :     # Copyright (c) 2003-2006 University of Chicago and Fellowship
3 :     # for Interpretations of Genomes. All Rights Reserved.
4 :     #
5 :     # This file is part of the SEED Toolkit.
6 :     #
7 :     # The SEED Toolkit is free software. You can redistribute
8 :     # it and/or modify it under the terms of the SEED Toolkit
9 :     # Public License.
10 :     #
11 :     # You should have received a copy of the SEED Toolkit Public License
12 :     # along with this program; if not write to the University of Chicago
13 :     # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14 :     # Genomes at veronika@thefig.info or download a copy from
15 :     # http://www.theseed.org/LICENSE.TXT.
16 :     #
17 :    
18 : olson 1.1 package Tracer;
19 :    
20 : parrello 1.12 require Exporter;
21 :     @ISA = ('Exporter');
22 : parrello 1.15 @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK);
23 : parrello 1.12 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
24 :     use strict;
25 :     use Carp qw(longmess croak);
26 :     use CGI;
27 :     use FIG_Config;
28 : parrello 1.9 use PageBuilder;
29 : parrello 1.21 use Digest::MD5;
30 : olson 1.1
31 :     =head1 Tracing and Debugging Helpers
32 :    
33 :     =head2 Introduction
34 :    
35 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
36 :     L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace
37 : parrello 1.2 message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself
38 :     has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
39 : olson 1.1 level is less than or equal to this package's trace level and whose category is activated will
40 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
41 : parrello 1.10 is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will
42 : olson 1.1 appear. To generate a trace message, use the following syntax.
43 :    
44 :     C<< Trace($message) if T(errors => 4); >>
45 :    
46 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
47 : parrello 1.3 category is active. Note that the special category C<main> is always active, so
48 : olson 1.1
49 : parrello 1.3 C<< Trace($message) if T(main => 4); >>
50 : olson 1.1
51 :     will trace if the trace level is 4 or more.
52 :    
53 :     If the category name is the same as the package name, all you need is the number. So, if the
54 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
55 :     active and the trace level is 2 or more.
56 :    
57 :     C<< Trace($message) if T(2); >>
58 :    
59 : parrello 1.10 To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list
60 : olson 1.1 of category names, and a set of options. The trace level and list of category names are
61 :     specified as a space-delimited string. Thus
62 :    
63 :     C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
64 :    
65 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
66 : parrello 1.12 specifies that messages should be output as HTML paragraphs.
67 :    
68 :     To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
69 :     level 3 and writes the output to the standard error output. This sort of thing might be
70 :     useful in a CGI environment.
71 :    
72 :     C<< TSetup('3 *', 'WARN'); >>
73 : olson 1.1
74 :     In addition to HTML and file output for trace messages, you can specify that the trace messages
75 :     be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
76 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
77 :     the page output, they can be gathered together and displayed at the end of the page. This makes
78 :     it easier to debug page formatting problems.
79 :    
80 : parrello 1.4 Finally, you can specify that all trace messages be emitted as warnings.
81 :    
82 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
83 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
84 :     Thus, debugging information is available and easily retrieved even when the application is
85 :     being used out in the field.
86 :    
87 : parrello 1.10 There is no hard and fast rule on how to use trace levels. The following is therefore only
88 :     a suggestion.
89 :    
90 :     =over 4
91 :    
92 :     =item 0 Error
93 :    
94 :     Message indicates an error that may lead to incorrect results or that has stopped the
95 :     application entirely.
96 :    
97 :     =item 1 Warning
98 :    
99 :     Message indicates something that is unexpected but that probably did not interfere
100 :     with program execution.
101 :    
102 :     =item 2 Notice
103 :    
104 :     Message indicates the beginning or end of a major task.
105 :    
106 :     =item 3 Information
107 :    
108 :     Message indicates a subtask. In the FIG system, a subtask generally relates to a single
109 :     genome. This would be a big loop that is not expected to execute more than 500 times or so.
110 :    
111 :     =item 4 Detail
112 :    
113 :     Message indicates a low-level loop iteration.
114 :    
115 :     =back
116 :    
117 : olson 1.1 =cut
118 : parrello 1.2
119 : olson 1.1 # Declare the configuration variables.
120 :    
121 : parrello 1.12 my $Destination = "NONE"; # Description of where to send the trace output.
122 :     my $TeeFlag = 0; # TRUE if output is going to a file and to the
123 :     # standard output
124 : parrello 1.3 my %Categories = ( main => 1 );
125 : parrello 1.12 # hash of active category names
126 :     my $TraceLevel = 0; # trace level; a higher trace level produces more
127 :     # messages
128 :     my @Queue = (); # queued list of trace messages.
129 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
130 : parrello 1.11 my $SetupCount = 0; # number of times TSetup called
131 : parrello 1.12 my $AllTrace = 0; # TRUE if we are tracing all categories.
132 : olson 1.1
133 :     =head2 Public Methods
134 :    
135 :     =head3 TSetup
136 :    
137 :     C<< TSetup($categoryList, $target); >>
138 :    
139 :     This method is used to specify the trace options. The options are stored as package data
140 :     and interrogated by the L</Trace> and L</T> methods.
141 :    
142 :     =over 4
143 :    
144 :     =item categoryList
145 :    
146 :     A string specifying the trace level and the categories to be traced, separated by spaces.
147 :     The trace level must come first.
148 :    
149 :     =item target
150 :    
151 :     The destination for the trace output. To send the trace output to a file, specify the file
152 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
153 : parrello 1.10 to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
154 :     symbol with a C<+> to echo output to a file AND to the standard output. In addition to
155 :     sending the trace messages to a file, you can specify a special destination. C<HTML> will
156 :     cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
157 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
158 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
159 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
160 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
161 : parrello 1.6 cause tracing to be suppressed.
162 : olson 1.1
163 :     =back
164 :    
165 :     =cut
166 :    
167 :     sub TSetup {
168 : parrello 1.12 # Get the parameters.
169 :     my ($categoryList, $target) = @_;
170 :     # Parse the category list.
171 :     my @categoryData = split /\s+/, $categoryList;
172 :     # Extract the trace level.
173 :     $TraceLevel = shift @categoryData;
174 :     # Presume category-based tracing until we learn otherwise.
175 :     $AllTrace = 0;
176 :     # Build the category hash. Note that if we find a "*", we turn on non-category
177 :     # tracing.
178 :     for my $category (@categoryData) {
179 :     if ($category eq '*') {
180 :     $AllTrace = 1;
181 :     } else {
182 : parrello 1.13 $Categories{lc $category} = 1;
183 : parrello 1.12 }
184 :     }
185 :     # Now we need to process the destination information. The most important special
186 :     # cases are the single ">", which requires we clear the file first, and the
187 :     # "+" prefix which indicates a double echo.
188 :     if ($target =~ m/^\+?>>?/) {
189 :     if ($target =~ m/^\+/) {
190 :     $TeeFlag = 1;
191 :     $target = substr($target, 1);
192 :     }
193 :     if ($target =~ m/^>[^>]/) {
194 :     open TRACEFILE, $target;
195 :     print TRACEFILE Now() . " Tracing initialized.\n";
196 :     close TRACEFILE;
197 :     $Destination = ">$target";
198 :     } else {
199 :     $Destination = $target;
200 :     }
201 :     } else {
202 :     $Destination = uc($target);
203 :     }
204 :     # Increment the setup counter.
205 :     $SetupCount++;
206 : parrello 1.11 }
207 :    
208 :     =head3 Setups
209 :    
210 :     C<< my $count = Tracer::Setups(); >>
211 :    
212 :     Return the number of times L</TSetup> has been called.
213 :    
214 :     This method allows for the creation of conditional tracing setups where, for example, we
215 :     may want to set up tracing if nobody else has done it before us.
216 :    
217 :     =cut
218 :    
219 :     sub Setups {
220 : parrello 1.12 return $SetupCount;
221 : olson 1.1 }
222 :    
223 : parrello 1.10 =head3 Open
224 :    
225 :     C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
226 :    
227 : parrello 1.11 Open a file.
228 : parrello 1.10
229 :     The I<$fileSpec> is essentially the second argument of the PERL C<open>
230 :     function. The mode is specified using Unix-like shell information. So, for
231 :     example,
232 :    
233 : parrello 1.12 Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
234 : parrello 1.10
235 :     would open for output appended to the specified file, and
236 :    
237 : parrello 1.12 Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
238 : parrello 1.10
239 :     would open a pipe that sorts the records written and removes duplicates. Note
240 : parrello 1.11 the use of file handle syntax in the Open call. To use anonymous file handles,
241 :     code as follows.
242 : parrello 1.10
243 : parrello 1.12 my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
244 : parrello 1.10
245 : parrello 1.11 The I<$message> parameter is used if the open fails. If it is set to C<0>, then
246 :     the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
247 :     failed open will throw an exception and the third parameter will be used to construct
248 :     an error message. If the parameter is omitted, a standard message is constructed
249 :     using the file spec.
250 : parrello 1.10
251 : parrello 1.12 Could not open "/usr/spool/news/twitlog"
252 : parrello 1.10
253 :     Note that the mode characters are automatically cleaned from the file name.
254 :     The actual error message from the file system will be captured and appended to the
255 :     message in any case.
256 :    
257 : parrello 1.12 Could not open "/usr/spool/news/twitlog": file not found.
258 : parrello 1.10
259 :     In some versions of PERL the only error message we get is a number, which
260 :     corresponds to the C++ C<errno> value.
261 :    
262 : parrello 1.12 Could not open "/usr/spool/news/twitlog": 6.
263 : parrello 1.10
264 :     =over 4
265 :    
266 :     =item fileHandle
267 :    
268 :     File handle. If this parameter is C<undef>, a file handle will be generated
269 :     and returned as the value of this method.
270 :    
271 :     =item fileSpec
272 :    
273 :     File name and mode, as per the PERL C<open> function.
274 :    
275 :     =item message (optional)
276 :    
277 :     Error message to use if the open fails. If omitted, a standard error message
278 :     will be generated. In either case, the error information from the file system
279 : parrello 1.11 is appended to the message. To specify a conditional open that does not throw
280 :     an error if it fails, use C<0>.
281 : parrello 1.10
282 :     =item RETURN
283 :    
284 : parrello 1.11 Returns the name of the file handle assigned to the file, or C<undef> if the
285 :     open failed.
286 : parrello 1.10
287 :     =back
288 :    
289 :     =cut
290 :    
291 :     sub Open {
292 : parrello 1.12 # Get the parameters.
293 :     my ($fileHandle, $fileSpec, $message) = @_;
294 :     # Attempt to open the file.
295 :     my $rv = open $fileHandle, $fileSpec;
296 :     # If the open failed, generate an error message.
297 :     if (! $rv) {
298 :     # Save the system error message.
299 :     my $sysMessage = $!;
300 :     # See if we need a default message.
301 :     if (!$message) {
302 :     # Clean any obvious mode characters and leading spaces from the
303 :     # filename.
304 :     my ($fileName) = FindNamePart($fileSpec);
305 :     $message = "Could not open \"$fileName\"";
306 :     }
307 :     # Terminate with an error using the supplied message and the
308 :     # error message from the file system.
309 :     Confess("$message: $!");
310 :     }
311 :     # Return the file handle.
312 :     return $fileHandle;
313 : parrello 1.10 }
314 :    
315 : parrello 1.11 =head3 FindNamePart
316 :    
317 :     C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>
318 :    
319 :     Extract the portion of a file specification that contains the file name.
320 :    
321 :     A file specification is the string passed to an C<open> call. It specifies the file
322 :     mode and name. In a truly complex situation, it can specify a pipe sequence. This
323 :     method assumes that the file name is whatever follows the first angle bracket
324 :     sequence. So, for example, in the following strings the file name is
325 :     C</usr/fig/myfile.txt>.
326 :    
327 :     >>/usr/fig/myfile.txt
328 :     </usr/fig/myfile.txt
329 :     | sort -u > /usr/fig/myfile.txt
330 :    
331 :     If the method cannot find a file name using its normal methods, it will return the
332 :     whole incoming string.
333 :    
334 :     =over 4
335 :    
336 :     =item fileSpec
337 :    
338 :     File specification string from which the file name is to be extracted.
339 :    
340 :     =item RETURN
341 :    
342 :     Returns a three-element list. The first element contains the file name portion of
343 :     the specified string, or the whole string if a file name cannot be found via normal
344 :     methods. The second element contains the start position of the file name portion and
345 :     the third element contains the length.
346 :    
347 :     =back
348 :    
349 :     =cut
350 :     #: Return Type $;
351 :     sub FindNamePart {
352 :     # Get the parameters.
353 :     my ($fileSpec) = @_;
354 : parrello 1.12 # Default to the whole input string.
355 :     my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
356 : parrello 1.11 # Parse out the file name if we can.
357 : parrello 1.12 if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
358 :     $retVal = $2;
359 :     $len = length $retVal;
360 :     $pos = (length $fileSpec) - (length $3) - $len;
361 :     }
362 : parrello 1.11 # Return the result.
363 :     return ($retVal, $pos, $len);
364 :     }
365 :    
366 :     =head3 OpenDir
367 :    
368 :     C<< my @files = OpenDir($dirName, $filtered); >>
369 :    
370 :     Open a directory and return all the file names. This function essentially performs
371 :     the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
372 :     set to TRUE, all filenames beginning with a period (C<.>) will be filtered out of
373 :     the return list. If the directory does not open, an exception is thrown. So,
374 :     for example,
375 :    
376 : parrello 1.12 my @files = OpenDir("/Volumes/fig/contigs", 1);
377 : parrello 1.29
378 : parrello 1.11 is effectively the same as
379 :    
380 : parrello 1.12 opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
381 :     my @files = grep { $_ !~ /^\./ } readdir(TMP);
382 : parrello 1.11
383 :     Similarly, the following code
384 :    
385 : parrello 1.12 my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs");
386 : parrello 1.29
387 : parrello 1.11 Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
388 :     automatically throws an error if the directory fails to open.
389 :    
390 :     =over 4
391 :    
392 :     =item dirName
393 :    
394 :     Name of the directory to open.
395 :    
396 :     =item filtered
397 :    
398 :     TRUE if files whose names begin with a period (C<.>) should be automatically removed
399 :     from the list, else FALSE.
400 :    
401 :     =back
402 :    
403 :     =cut
404 :     #: Return Type @;
405 :     sub OpenDir {
406 :     # Get the parameters.
407 :     my ($dirName, $filtered) = @_;
408 :     # Declare the return variable.
409 :     my @retVal;
410 : parrello 1.12 # Open the directory.
411 :     if (opendir(my $dirHandle, $dirName)) {
412 :     # The directory opened successfully. Get the appropriate list according to the
413 :     # strictures of the filter parameter.
414 :     if ($filtered) {
415 :     @retVal = grep { $_ !~ /^\./ } readdir $dirHandle;
416 :     } else {
417 :     @retVal = readdir $dirHandle;
418 :     }
419 :     } else {
420 :     # Here the directory would not open.
421 :     Confess("Could not open directory $dirName.");
422 :     }
423 : parrello 1.11 # Return the result.
424 :     return @retVal;
425 :     }
426 :    
427 : parrello 1.6 =head3 SetLevel
428 :    
429 :     C<< Tracer::SetLevel($newLevel); >>
430 :    
431 :     Modify the trace level. A higher trace level will cause more messages to appear.
432 :    
433 :     =over 4
434 :    
435 :     =item newLevel
436 :    
437 :     Proposed new trace level.
438 :    
439 :     =back
440 :    
441 :     =cut
442 :    
443 :     sub SetLevel {
444 :     $TraceLevel = $_[0];
445 :     }
446 :    
447 : olson 1.1 =head3 Now
448 :    
449 :     C<< my $string = Tracer::Now(); >>
450 :    
451 :     Return a displayable time stamp containing the local time.
452 :    
453 :     =cut
454 :    
455 :     sub Now {
456 : parrello 1.12 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
457 :     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
458 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
459 :     return $retVal;
460 : olson 1.1 }
461 :    
462 :     # Pad a number to 2 digits.
463 :     sub _p2 {
464 : parrello 1.12 my ($value) = @_;
465 :     $value = "0$value" if ($value < 10);
466 :     return $value;
467 : olson 1.1 }
468 :    
469 :     =head3 LogErrors
470 :    
471 :     C<< Tracer::LogErrors($fileName); >>
472 :    
473 :     Route the standard error output to a log file.
474 :    
475 :     =over 4
476 :    
477 :     =item fileName
478 :    
479 :     Name of the file to receive the error output.
480 :    
481 :     =back
482 :    
483 :     =cut
484 :    
485 :     sub LogErrors {
486 : parrello 1.12 # Get the file name.
487 :     my ($fileName) = @_;
488 :     # Open the file as the standard error output.
489 :     open STDERR, '>', $fileName;
490 : olson 1.1 }
491 :    
492 : parrello 1.5 =head3 ReadOptions
493 :    
494 :     C<< my %options = Tracer::ReadOptions($fileName); >>
495 :    
496 :     Read a set of options from a file. Each option is encoded in a line of text that has the
497 :     format
498 :    
499 :     I<optionName>C<=>I<optionValue>C<; >I<comment>
500 :    
501 :     The option name must consist entirely of letters, digits, and the punctuation characters
502 : parrello 1.9 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
503 :     character is a semi-colon will be ignored. The return hash will map each option name to
504 : parrello 1.5 the corresponding option value.
505 :    
506 :     =over 4
507 :    
508 :     =item fileName
509 :    
510 :     Name of the file containing the option data.
511 :    
512 :     =item RETURN
513 :    
514 :     Returns a hash mapping the option names specified in the file to their corresponding option
515 :     value.
516 :    
517 :     =back
518 :    
519 :     =cut
520 :    
521 :     sub ReadOptions {
522 : parrello 1.12 # Get the parameters.
523 :     my ($fileName) = @_;
524 :     # Open the file.
525 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
526 :     # Count the number of records read.
527 :     my ($records, $comments) = 0;
528 :     # Create the return hash.
529 :     my %retVal = ();
530 :     # Loop through the file, accumulating key-value pairs.
531 :     while (my $line = <CONFIGFILE>) {
532 :     # Denote we've read a line.
533 :     $records++;
534 :     # Determine the line type.
535 :     if ($line =~ /^\s*[\n\r]/) {
536 :     # A blank line is a comment.
537 :     $comments++;
538 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
539 :     # Here we have an option assignment.
540 :     retVal{$1} = $2;
541 :     } elsif ($line =~ /^\s*;/) {
542 :     # Here we have a text comment.
543 :     $comments++;
544 :     } else {
545 :     # Here we have an invalid line.
546 :     Trace("Invalid option statement in record $records.") if T(0);
547 :     }
548 :     }
549 :     # Return the hash created.
550 :     return %retVal;
551 : parrello 1.5 }
552 :    
553 : olson 1.1 =head3 GetOptions
554 :    
555 :     C<< Tracer::GetOptions(\%defaults, \%options); >>
556 :    
557 :     Merge a specified set of options into a table of defaults. This method takes two hash references
558 :     as input and uses the data from the second to update the first. If the second does not exist,
559 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
560 :     exist in the first.
561 :    
562 :     Consider the following example.
563 :    
564 :     C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
565 :    
566 :     In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
567 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
568 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
569 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
570 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
571 :    
572 :     C<< {databaseType => 'Oracle'} >>
573 :    
574 :     an error will occur because the B<databaseType> option does not exist.
575 :    
576 :     =over 4
577 :    
578 :     =item defaults
579 :    
580 :     Table of default option values.
581 :    
582 :     =item options
583 :    
584 :     Table of overrides, if any.
585 :    
586 :     =item RETURN
587 :    
588 :     Returns a reference to the default table passed in as the first parameter.
589 :    
590 :     =back
591 :    
592 :     =cut
593 :    
594 :     sub GetOptions {
595 : parrello 1.12 # Get the parameters.
596 :     my ($defaults, $options) = @_;
597 :     # Check for overrides.
598 :     if ($options) {
599 :     # Loop through the overrides.
600 :     while (my ($option, $setting) = each %{$options}) {
601 :     # Insure this override exists.
602 :     if (!exists $defaults->{$option}) {
603 :     croak "Unrecognized option $option encountered.";
604 :     } else {
605 :     # Apply the override.
606 :     $defaults->{$option} = $setting;
607 :     }
608 :     }
609 :     }
610 :     # Return the merged table.
611 :     return $defaults;
612 : olson 1.1 }
613 :    
614 :     =head3 MergeOptions
615 :    
616 :     C<< Tracer::MergeOptions(\%table, \%defaults); >>
617 :    
618 :     Merge default values into a hash table. This method looks at the key-value pairs in the
619 :     second (default) hash, and if a matching key is not found in the first hash, the default
620 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
621 :     checking and no return value.
622 :    
623 :     =over 4
624 :    
625 :     =item table
626 :    
627 :     Hash table to be updated with the default values.
628 :    
629 :     =item defaults
630 :    
631 :     Default values to be merged into the first hash table if they are not already present.
632 :    
633 :     =back
634 :    
635 :     =cut
636 :    
637 :     sub MergeOptions {
638 : parrello 1.12 # Get the parameters.
639 :     my ($table, $defaults) = @_;
640 :     # Loop through the defaults.
641 :     while (my ($key, $value) = each %{$defaults}) {
642 :     if (!exists $table->{$key}) {
643 :     $table->{$key} = $value;
644 :     }
645 :     }
646 : olson 1.1 }
647 :    
648 :     =head3 Trace
649 :    
650 :     C<< Trace($message); >>
651 :    
652 :     Write a trace message to the target location specified in L</TSetup>. If there has not been
653 :     any prior call to B<TSetup>.
654 :    
655 :     =over 4
656 :    
657 :     =item message
658 :    
659 :     Message to write.
660 :    
661 :     =back
662 :    
663 :     =cut
664 :    
665 :     sub Trace {
666 : parrello 1.12 # Get the parameters.
667 :     my ($message) = @_;
668 :     # Get the timestamp.
669 :     my $timeStamp = Now();
670 :     # Format the message. Note we strip off any line terminators at the end.
671 :     my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
672 :     # Process according to the destination.
673 :     if ($Destination eq "TEXT") {
674 :     # Write the message to the standard output.
675 :     print "$formatted\n";
676 :     } elsif ($Destination eq "ERROR") {
677 :     # Write the message to the error output.
678 :     print STDERR "$formatted\n";
679 :     } elsif ($Destination eq "QUEUE") {
680 :     # Push the message into the queue.
681 :     push @Queue, "$formatted";
682 :     } elsif ($Destination eq "HTML") {
683 :     # Convert the message to HTML and write it to the standard output.
684 :     my $escapedMessage = CGI::escapeHTML($message);
685 :     print "<p>$formatted</p>\n";
686 : parrello 1.4 } elsif ($Destination eq "WARN") {
687 :     # Emit the message as a warning.
688 :     warn $message;
689 : parrello 1.12 } elsif ($Destination =~ m/^>>/) {
690 :     # Write the trace message to an output file.
691 : parrello 1.14 (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
692 : parrello 1.12 print TRACING "$formatted\n";
693 :     close TRACING;
694 :     # If the Tee flag is on, echo it to the standard output.
695 :     if ($TeeFlag) {
696 :     print "$formatted\n";
697 :     }
698 :     }
699 : olson 1.1 }
700 :    
701 :     =head3 T
702 :    
703 : parrello 1.2 C<< my $switch = T($category, $traceLevel); >>
704 : olson 1.1
705 : parrello 1.12 or
706 : parrello 1.2
707 : olson 1.1 C<< my $switch = T($traceLevel); >>
708 :    
709 :     Return TRUE if the trace level is at or above a specified value and the specified category
710 :     is active, else FALSE. If no category is specified, the caller's package name is used.
711 :    
712 :     =over 4
713 :    
714 :     =item category
715 :    
716 :     Category to which the message belongs. If not specified, the caller's package name is
717 :     used.
718 :    
719 :     =item traceLevel
720 :    
721 :     Relevant tracing level.
722 :    
723 :     =item RETURN
724 :    
725 :     TRUE if a message at the specified trace level would appear in the trace, else FALSE.
726 :    
727 :     =back
728 :    
729 :     =cut
730 :    
731 :     sub T {
732 : parrello 1.12 # Declare the return variable.
733 :     my $retVal = 0;
734 :     # Only proceed if tracing is turned on.
735 :     if ($Destination ne "NONE") {
736 :     # Get the parameters.
737 :     my ($category, $traceLevel) = @_;
738 :     if (!defined $traceLevel) {
739 :     # Here we have no category, so we need to get the calling package.
740 :     # The calling package is normally the first parameter. If it is
741 :     # omitted, the first parameter will be the tracelevel. So, the
742 :     # first thing we do is shift the so-called category into the
743 :     # $traceLevel variable where it belongs.
744 :     $traceLevel = $category;
745 :     my ($package, $fileName, $line) = caller;
746 : parrello 1.3 # If there is no calling package, we default to "main".
747 : parrello 1.12 if (!$package) {
748 : parrello 1.3 $category = "main";
749 : parrello 1.12 } else {
750 :     $category = $package;
751 :     }
752 :     }
753 : parrello 1.7 # Save the category name.
754 :     $LastCategory = $category;
755 : parrello 1.13 # Convert it to lower case before we hash it.
756 :     $category = lc $category;
757 : parrello 1.12 # Use the category and tracelevel to compute the result.
758 :     $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
759 : parrello 1.3 }
760 : parrello 1.12 # Return the computed result.
761 : parrello 1.3 return $retVal;
762 : olson 1.1 }
763 :    
764 :     =head3 ParseCommand
765 :    
766 :     C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
767 :    
768 :     Parse a command line consisting of a list of parameters. The initial parameters may be option
769 : parrello 1.2 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
770 :     off and merged into a table of default options. The remainder of the command line is
771 : olson 1.1 returned as a list of positional arguments. For example, consider the following invocation.
772 :    
773 :     C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
774 :    
775 :     In this case, the list @words will be treated as a command line. There are two options available,
776 :     B<errors> and B<logFile>. If @words has the following format
777 :    
778 :     C<< -logFile=error.log apple orange rutabaga >>
779 :    
780 :     then at the end of the invocation, C<$options> will be
781 :    
782 :     C<< { errors => 0, logFile => 'error.log' } >>
783 :    
784 :     and C<@arguments> will contain
785 :    
786 :     C<< apple orange rutabaga >>
787 :    
788 : parrello 1.2 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
789 : olson 1.1 support for quote characters.
790 :    
791 :     =over 4
792 :    
793 :     =item optionTable
794 :    
795 :     Table of default options.
796 :    
797 :     =item inputList
798 :    
799 :     List of words on the command line.
800 :    
801 :     =item RETURN
802 :    
803 :     Returns a reference to the option table and a list of the positional arguments.
804 :    
805 :     =back
806 :    
807 :     =cut
808 :    
809 :     sub ParseCommand {
810 : parrello 1.12 # Get the parameters.
811 :     my ($optionTable, @inputList) = @_;
812 :     # Process any options in the input list.
813 :     my %overrides = ();
814 :     while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
815 :     # Get the current option.
816 :     my $arg = shift @inputList;
817 :     # Pull out the option name.
818 :     $arg =~ /^-([^=]*)/g;
819 :     my $name = $1;
820 :     # Check for an option value.
821 :     if ($arg =~ /\G=(.*)$/g) {
822 :     # Here we have a value for the option.
823 :     $overrides{$name} = UnEscape($1);
824 :     } else {
825 :     # Here there is no value, so we use 1.
826 :     $overrides{$name} = 1;
827 :     }
828 :     }
829 :     # Merge the options into the defaults.
830 :     GetOptions($optionTable, \%overrides);
831 :     # Translate the remaining parameters.
832 :     my @retVal = ();
833 :     for my $inputParm (@inputList) {
834 :     push @retVal, UnEscape($inputParm);
835 :     }
836 :     # Return the results.
837 :     return ($optionTable, @retVal);
838 : olson 1.1 }
839 :    
840 : parrello 1.9 =head3 Escape
841 :    
842 :     C<< my $codedString = Tracer::Escape($realString); >>
843 :    
844 : parrello 1.25 Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines
845 : parrello 1.28 replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
846 :     result is to reverse the effect of L</UnEscape>.
847 : parrello 1.9
848 :     =over 4
849 :    
850 :     =item realString
851 :    
852 :     String to escape.
853 :    
854 :     =item RETURN
855 :    
856 :     Escaped equivalent of the real string.
857 :    
858 :     =back
859 :    
860 :     =cut
861 :    
862 :     sub Escape {
863 : parrello 1.12 # Get the parameter.
864 :     my ($realString) = @_;
865 :     # Initialize the return variable.
866 :     my $retVal = "";
867 :     # Loop through the parameter string, looking for sequences to escape.
868 :     while (length $realString > 0) {
869 :     # Look for the first sequence to escape.
870 : parrello 1.27 if ($realString =~ /^(.*?)([\n\t\r\\])/) {
871 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
872 :     # itself is in $2. First, move the clear text to the return variable.
873 :     $retVal .= $1;
874 : parrello 1.14 # Strip the processed section off the real string.
875 :     $realString = substr $realString, (length $2) + (length $1);
876 : parrello 1.28 # Get the matched character.
877 : parrello 1.12 my $char = $2;
878 : parrello 1.28 # If we have a CR, we are done.
879 :     if ($char ne "\r") {
880 :     # It's not a CR, so encode the escape sequence.
881 :     $char =~ tr/\t\n/tn/;
882 :     $retVal .= "\\" . $char;
883 :     }
884 : parrello 1.12 } else {
885 :     # Here there are no more escape sequences. The rest of the string is
886 :     # transferred unmodified.
887 :     $retVal .= $realString;
888 :     $realString = "";
889 :     }
890 :     }
891 :     # Return the result.
892 :     return $retVal;
893 : parrello 1.9 }
894 :    
895 : olson 1.1 =head3 UnEscape
896 :    
897 :     C<< my $realString = Tracer::UnEscape($codedString); >>
898 :    
899 : parrello 1.25 Replace escape sequences with their actual equivalents. C<\t> will be replaced by
900 : parrello 1.28 a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
901 :     be deleted.
902 : olson 1.1
903 :     =over 4
904 :    
905 :     =item codedString
906 :    
907 :     String to un-escape.
908 :    
909 :     =item RETURN
910 :    
911 :     Returns a copy of the original string with the escape sequences converted to their actual
912 :     values.
913 :    
914 :     =back
915 :    
916 :     =cut
917 :    
918 :     sub UnEscape {
919 : parrello 1.12 # Get the parameter.
920 :     my ($codedString) = @_;
921 :     # Initialize the return variable.
922 :     my $retVal = "";
923 :     # Only proceed if the incoming string is nonempty.
924 :     if (defined $codedString) {
925 :     # Loop through the parameter string, looking for escape sequences. We can't do
926 : parrello 1.25 # translating because it causes problems with the escaped slash. ("\\t" becomes
927 :     # "\<tab>" no matter what we do.)
928 : parrello 1.12 while (length $codedString > 0) {
929 :     # Look for the first escape sequence.
930 : parrello 1.27 if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
931 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
932 :     # itself is in $2. First, move the clear text to the return variable.
933 :     $retVal .= $1;
934 :     $codedString = substr $codedString, (2 + length $1);
935 : parrello 1.28 # Get the escape value.
936 : parrello 1.12 my $char = $2;
937 : parrello 1.28 # If we have a "\r", we are done.
938 :     if ($char ne 'r') {
939 :     # Here it's not an 'r', so we convert it.
940 :     $char =~ tr/\\tn/\\\t\n/;
941 :     $retVal .= $char;
942 :     }
943 : parrello 1.12 } else {
944 :     # Here there are no more escape sequences. The rest of the string is
945 :     # transferred unmodified.
946 :     $retVal .= $codedString;
947 :     $codedString = "";
948 :     }
949 :     }
950 :     }
951 :     # Return the result.
952 :     return $retVal;
953 : olson 1.1 }
954 :    
955 :     =head3 ParseRecord
956 :    
957 :     C<< my @fields = Tracer::ParseRecord($line); >>
958 :    
959 :     Parse a tab-delimited data line. The data line is split into field values. Embedded tab
960 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
961 :     These will automatically be converted.
962 :    
963 :     =over 4
964 :    
965 :     =item line
966 :    
967 :     Line of data containing the tab-delimited fields.
968 :    
969 :     =item RETURN
970 :    
971 :     Returns a list of the fields found in the data line.
972 :    
973 :     =back
974 :    
975 :     =cut
976 :    
977 :     sub ParseRecord {
978 : parrello 1.12 # Get the parameter.
979 :     my ($line) = @_;
980 :     # Remove the trailing new-line, if any.
981 :     chomp $line;
982 :     # Split the line read into pieces using the tab character.
983 :     my @retVal = split /\t/, $line;
984 :     # Trim and fix the escapes in each piece.
985 :     for my $value (@retVal) {
986 :     # Trim leading whitespace.
987 :     $value =~ s/^\s+//;
988 :     # Trim trailing whitespace.
989 :     $value =~ s/\s+$//;
990 :     # Delete the carriage returns.
991 :     $value =~ s/\r//g;
992 :     # Convert the escapes into their real values.
993 :     $value =~ s/\\t/"\t"/ge;
994 :     $value =~ s/\\n/"\n"/ge;
995 :     }
996 :     # Return the result.
997 :     return @retVal;
998 : olson 1.1 }
999 :    
1000 :     =head3 Merge
1001 :    
1002 :     C<< my @mergedList = Tracer::Merge(@inputList); >>
1003 :    
1004 :     Sort a list of strings and remove duplicates.
1005 :    
1006 :     =over 4
1007 :    
1008 :     =item inputList
1009 :    
1010 :     List of scalars to sort and merge.
1011 :    
1012 :     =item RETURN
1013 :    
1014 :     Returns a list containing the same elements sorted in ascending order with duplicates
1015 :     removed.
1016 :    
1017 :     =back
1018 :    
1019 :     =cut
1020 :    
1021 :     sub Merge {
1022 : parrello 1.12 # Get the input list in sort order.
1023 :     my @inputList = sort @_;
1024 :     # Only proceed if the list has at least two elements.
1025 :     if (@inputList > 1) {
1026 :     # Now we want to move through the list splicing out duplicates.
1027 :     my $i = 0;
1028 :     while ($i < @inputList) {
1029 :     # Get the current entry.
1030 :     my $thisEntry = $inputList[$i];
1031 :     # Find out how many elements duplicate the current entry.
1032 :     my $j = $i + 1;
1033 :     my $dup1 = $i + 1;
1034 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
1035 :     # If the number is nonzero, splice out the duplicates found.
1036 :     if ($j > $dup1) {
1037 :     splice @inputList, $dup1, $j - $dup1;
1038 :     }
1039 :     # Now the element at position $dup1 is different from the element before it
1040 :     # at position $i. We push $i forward one position and start again.
1041 :     $i++;
1042 :     }
1043 :     }
1044 :     # Return the merged list.
1045 :     return @inputList;
1046 : olson 1.1 }
1047 :    
1048 :     =head3 GetFile
1049 :    
1050 : parrello 1.6 C<< my @fileContents = Tracer::GetFile($fileName); >>
1051 : olson 1.1
1052 :     Return the entire contents of a file.
1053 :    
1054 :     =over 4
1055 :    
1056 :     =item fileName
1057 :    
1058 :     Name of the file to read.
1059 :    
1060 :     =item RETURN
1061 :    
1062 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
1063 :     In a scalar context, returns the entire file as a string.
1064 : olson 1.1
1065 :     =back
1066 :    
1067 :     =cut
1068 :    
1069 :     sub GetFile {
1070 : parrello 1.12 # Get the parameters.
1071 :     my ($fileName) = @_;
1072 :     # Declare the return variable.
1073 :     my @retVal = ();
1074 :     # Open the file for input.
1075 :     my $ok = open INPUTFILE, "<$fileName";
1076 :     if (!$ok) {
1077 :     # If we had an error, trace it. We will automatically return a null value.
1078 : parrello 1.16 Trace("Could not open \"$fileName\" for input: $!") if T(0);
1079 : parrello 1.12 } else {
1080 :     # Read the whole file into the return variable, stripping off any terminator
1081 : parrello 1.6 # characters.
1082 :     my $lineCount = 0;
1083 : parrello 1.12 while (my $line = <INPUTFILE>) {
1084 : parrello 1.6 $lineCount++;
1085 : parrello 1.9 $line = Strip($line);
1086 : parrello 1.12 push @retVal, $line;
1087 :     }
1088 :     # Close it.
1089 :     close INPUTFILE;
1090 : parrello 1.6 my $actualLines = @retVal;
1091 : parrello 1.12 }
1092 :     # Return the file's contents in the desired format.
1093 : parrello 1.9 if (wantarray) {
1094 : parrello 1.12 return @retVal;
1095 : parrello 1.6 } else {
1096 :     return join "\n", @retVal;
1097 :     }
1098 : olson 1.1 }
1099 :    
1100 :     =head3 QTrace
1101 :    
1102 :     C<< my $data = QTrace($format); >>
1103 :    
1104 :     Return the queued trace data in the specified format.
1105 :    
1106 :     =over 4
1107 :    
1108 :     =item format
1109 :    
1110 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
1111 :    
1112 :     =back
1113 :    
1114 :     =cut
1115 :    
1116 :     sub QTrace {
1117 : parrello 1.12 # Get the parameter.
1118 :     my ($format) = @_;
1119 :     # Create the return variable.
1120 :     my $retVal = "";
1121 : parrello 1.14 # Only proceed if there is an actual queue.
1122 :     if (@Queue) {
1123 :     # Process according to the format.
1124 :     if ($format =~ m/^HTML$/i) {
1125 :     # Convert the queue into an HTML list.
1126 :     $retVal = "<ul>\n";
1127 :     for my $line (@Queue) {
1128 :     my $escapedLine = CGI::escapeHTML($line);
1129 :     $retVal .= "<li>$escapedLine</li>\n";
1130 :     }
1131 :     $retVal .= "</ul>\n";
1132 :     } elsif ($format =~ m/^TEXT$/i) {
1133 :     # Convert the queue into a list of text lines.
1134 :     $retVal = join("\n", @Queue) . "\n";
1135 :     }
1136 :     # Clear the queue.
1137 :     @Queue = ();
1138 : parrello 1.12 }
1139 :     # Return the formatted list.
1140 :     return $retVal;
1141 : olson 1.1 }
1142 :    
1143 :     =head3 Confess
1144 :    
1145 :     C<< Confess($message); >>
1146 :    
1147 : parrello 1.22 Trace the call stack and abort the program with the specified message. When used with
1148 : parrello 1.9 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
1149 : parrello 1.6 So, for example
1150 : olson 1.1
1151 : parrello 1.6 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1152 : olson 1.1
1153 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1154 :    
1155 :     =over 4
1156 :    
1157 :     =item message
1158 :    
1159 :     Message to include in the trace.
1160 :    
1161 :     =back
1162 :    
1163 :     =cut
1164 :    
1165 :     sub Confess {
1166 : parrello 1.12 # Get the parameters.
1167 :     my ($message) = @_;
1168 :     # Trace the call stack.
1169 : parrello 1.22 Cluck($message);
1170 : parrello 1.12 # Abort the program.
1171 :     croak(">>> $message");
1172 : olson 1.1 }
1173 :    
1174 : parrello 1.6 =head3 Assert
1175 :    
1176 :     C<< Assert($condition1, $condition2, ... $conditionN); >>
1177 :    
1178 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
1179 : parrello 1.29 the OR operator and the L</Confess> method as a debugging assert.
1180 : parrello 1.6 So, for example
1181 :    
1182 :     C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1183 :    
1184 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1185 :    
1186 :     =cut
1187 :     sub Assert {
1188 :     my $retVal = 1;
1189 :     LOOP: for my $condition (@_) {
1190 :     if (! $condition) {
1191 :     $retVal = 0;
1192 :     last LOOP;
1193 :     }
1194 :     }
1195 :     return $retVal;
1196 :     }
1197 :    
1198 : olson 1.1 =head3 Cluck
1199 :    
1200 :     C<< Cluck($message); >>
1201 :    
1202 :     Trace the call stack. Note that for best results, you should qualify the call with a
1203 :     trace condition. For example,
1204 :    
1205 :     C<< Cluck("Starting record parse.") if T(3); >>
1206 :    
1207 :     will only trace the stack if the trace level for the package is 3 or more.
1208 :    
1209 :     =over 4
1210 :    
1211 :     =item message
1212 :    
1213 :     Message to include in the trace.
1214 :    
1215 :     =back
1216 :    
1217 :     =cut
1218 :    
1219 :     sub Cluck {
1220 : parrello 1.12 # Get the parameters.
1221 :     my ($message) = @_;
1222 : parrello 1.5 # Trace what's happening.
1223 :     Trace("Stack trace for event: $message");
1224 : parrello 1.12 my $confession = longmess($message);
1225 :     # Convert the confession to a series of trace messages. Note we skip any
1226 : parrello 1.5 # messages relating to calls into Tracer.
1227 : parrello 1.12 for my $line (split /\s*\n/, $confession) {
1228 :     Trace($line) if ($line !~ /Tracer\.pm/);
1229 :     }
1230 : olson 1.1 }
1231 :    
1232 : parrello 1.5 =head3 Min
1233 :    
1234 :     C<< my $min = Min($value1, $value2, ... $valueN); >>
1235 :    
1236 :     Return the minimum argument. The arguments are treated as numbers.
1237 :    
1238 :     =over 4
1239 :    
1240 :     =item $value1, $value2, ... $valueN
1241 :    
1242 :     List of numbers to compare.
1243 :    
1244 :     =item RETURN
1245 :    
1246 :     Returns the lowest number in the list.
1247 :    
1248 :     =back
1249 :    
1250 :     =cut
1251 :    
1252 :     sub Min {
1253 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1254 :     my ($retVal, @values) = @_;
1255 :     # Loop through the remaining parameters, looking for the lowest.
1256 :     for my $value (@values) {
1257 :     if ($value < $retVal) {
1258 :     $retVal = $value;
1259 :     }
1260 :     }
1261 :     # Return the minimum found.
1262 :     return $retVal;
1263 : parrello 1.5 }
1264 :    
1265 :     =head3 Max
1266 :    
1267 :     C<< my $max = Max($value1, $value2, ... $valueN); >>
1268 :    
1269 :     Return the maximum argument. The arguments are treated as numbers.
1270 :    
1271 :     =over 4
1272 :    
1273 :     =item $value1, $value2, ... $valueN
1274 :    
1275 :     List of numbers to compare.
1276 :    
1277 :     =item RETURN
1278 :    
1279 :     Returns the highest number in the list.
1280 :    
1281 :     =back
1282 :    
1283 :     =cut
1284 :    
1285 :     sub Max {
1286 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1287 :     my ($retVal, @values) = @_;
1288 :     # Loop through the remaining parameters, looking for the highest.
1289 :     for my $value (@values) {
1290 :     if ($value > $retVal) {
1291 :     $retVal = $value;
1292 :     }
1293 :     }
1294 :     # Return the maximum found.
1295 :     return $retVal;
1296 : parrello 1.5 }
1297 :    
1298 :     =head3 AddToListMap
1299 :    
1300 :     C<< Tracer::AddToListMap(\%hash, $key, $value); >>
1301 :    
1302 :     Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1303 :     is created for the key. Otherwise, the new value is pushed onto the list.
1304 :    
1305 :     =over 4
1306 :    
1307 :     =item hash
1308 :    
1309 :     Reference to the target hash.
1310 :    
1311 :     =item key
1312 :    
1313 :     Key for which the value is to be added.
1314 :    
1315 :     =item value
1316 :    
1317 :     Value to add to the key's value list.
1318 :    
1319 :     =back
1320 :    
1321 :     =cut
1322 :    
1323 :     sub AddToListMap {
1324 :     # Get the parameters.
1325 :     my ($hash, $key, $value) = @_;
1326 :     # Process according to whether or not the key already has a value.
1327 :     if (! exists $hash->{$key}) {
1328 :     $hash->{$key} = [$value];
1329 :     } else {
1330 :     push @{$hash->{$key}}, $value;
1331 :     }
1332 :     }
1333 : olson 1.1
1334 : parrello 1.7 =head3 DebugMode
1335 :    
1336 :     C<< if (Tracer::DebugMode) { ...code... } >>
1337 :    
1338 : parrello 1.22 Return TRUE if debug mode has been turned on, else output an error
1339 :     page and return FALSE.
1340 : parrello 1.7
1341 :     Certain CGI scripts are too dangerous to exist in the production
1342 :     environment. This method provides a simple way to prevent them
1343 : parrello 1.21 from working unless they are explicitly turned on by creating a password
1344 :     cookie via the B<SetPassword> script. If debugging mode
1345 : parrello 1.22 is not turned on, an error web page will be output directing the
1346 :     user to enter in the correct password.
1347 : parrello 1.7
1348 :     =cut
1349 :    
1350 :     sub DebugMode {
1351 : parrello 1.12 # Declare the return variable.
1352 : parrello 1.21 my $retVal = 0;
1353 : parrello 1.12 # Check the debug configuration.
1354 : parrello 1.21 my $password = CGI::cookie("DebugMode");
1355 :     my $encrypted = Digest::MD5::md5_hex($password);
1356 :     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
1357 : parrello 1.12 $retVal = 1;
1358 :     } else {
1359 :     # Here debug mode is off, so we generate an error page.
1360 : parrello 1.9 my $pageString = PageBuilder::Build("<Html/ErrorPage.html", {}, "Html");
1361 : parrello 1.12 print $pageString;
1362 :     }
1363 :     # Return the determination indicator.
1364 : parrello 1.18 return $retVal;
1365 : parrello 1.9 }
1366 :    
1367 :     =head3 Strip
1368 :    
1369 :     C<< my $string = Tracer::Strip($line); >>
1370 :    
1371 :     Strip all line terminators off a string. This is necessary when dealing with files
1372 :     that may have been transferred back and forth several times among different
1373 :     operating environments.
1374 :    
1375 :     =over 4
1376 :    
1377 :     =item line
1378 :    
1379 :     Line of text to be stripped.
1380 :    
1381 :     =item RETURN
1382 :    
1383 :     The same line of text with all the line-ending characters chopped from the end.
1384 :    
1385 :     =back
1386 :    
1387 :     =cut
1388 :    
1389 :     sub Strip {
1390 : parrello 1.12 # Get a copy of the parameter string.
1391 :     my ($string) = @_;
1392 : parrello 1.29 my $retVal = (defined $string ? $string : "");
1393 : parrello 1.9 # Strip the line terminator characters.
1394 :     $retVal =~ s/(\r|\n)+$//g;
1395 : parrello 1.12 # Return the result.
1396 :     return $retVal;
1397 : parrello 1.9 }
1398 :    
1399 :     =head3 Pad
1400 :    
1401 :     C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1402 :    
1403 :     Pad a string to a specified length. The pad character will be a
1404 :     space, and the padding will be on the right side unless specified
1405 :     in the third parameter.
1406 :    
1407 :     =over 4
1408 :    
1409 :     =item string
1410 :    
1411 :     String to be padded.
1412 :    
1413 :     =item len
1414 :    
1415 :     Desired length of the padded string.
1416 :    
1417 :     =item left (optional)
1418 :    
1419 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1420 :    
1421 :     =item padChar (optional)
1422 :    
1423 : parrello 1.22 Character to use for padding. The default is a space.
1424 :    
1425 : parrello 1.9 =item RETURN
1426 :    
1427 : parrello 1.22 Returns a copy of the original string with the pad character added to the
1428 :     specified end so that it achieves the desired length.
1429 : parrello 1.9
1430 :     =back
1431 :    
1432 :     =cut
1433 :    
1434 :     sub Pad {
1435 : parrello 1.12 # Get the parameters.
1436 :     my ($string, $len, $left, $padChar) = @_;
1437 :     # Compute the padding character.
1438 :     if (! defined $padChar) {
1439 :     $padChar = " ";
1440 :     }
1441 :     # Compute the number of spaces needed.
1442 :     my $needed = $len - length $string;
1443 :     # Copy the string into the return variable.
1444 :     my $retVal = $string;
1445 :     # Only proceed if padding is needed.
1446 :     if ($needed > 0) {
1447 :     # Create the pad string.
1448 :     my $pad = $padChar x $needed;
1449 :     # Affix it to the return value.
1450 :     if ($left) {
1451 :     $retVal = $pad . $retVal;
1452 :     } else {
1453 :     $retVal .= $pad;
1454 :     }
1455 :     }
1456 :     # Return the result.
1457 :     return $retVal;
1458 : parrello 1.7 }
1459 :    
1460 : parrello 1.29 =head3 EOF
1461 :    
1462 :     This is a constant that is lexically greater than any useful string.
1463 :    
1464 :     =cut
1465 :    
1466 :     sub EOF {
1467 :     return "\xFF\xFF\xFF\xFF\xFF";
1468 :     }
1469 :    
1470 : parrello 1.15 =head3 TICK
1471 :    
1472 :     C<< my @results = TICK($commandString); >>
1473 :    
1474 :     Perform a back-tick operation on a command. If this is a Windows environment, any leading
1475 :     dot-slash (C<./> will be removed. So, for example, if you were doing
1476 :    
1477 :     `./protein.cgi`
1478 :    
1479 :     from inside a CGI script, it would work fine in Unix, but would issue an error message
1480 :     in Windows complaining that C<'.'> is not a valid command. If instead you code
1481 :    
1482 :     TICK("./protein.cgi")
1483 :    
1484 :     it will work correctly in both environments.
1485 :    
1486 :     =over 4
1487 :    
1488 :     =item commandString
1489 :    
1490 :     The command string to pass to the system.
1491 :    
1492 :     =item RETURN
1493 :    
1494 :     Returns the standard output from the specified command, as a list.
1495 :    
1496 :     =back
1497 :    
1498 :     =cut
1499 :     #: Return Type @;
1500 :     sub TICK {
1501 :     # Get the parameters.
1502 :     my ($commandString) = @_;
1503 :     # Chop off the dot-slash if this is Windows.
1504 :     if ($FIG_Config::win_mode) {
1505 :     $commandString =~ s!^\./!!;
1506 :     }
1507 :     # Activate the command and return the result.
1508 :     return `$commandString`;
1509 :     }
1510 :    
1511 : redwards 1.8 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3