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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3