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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3