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

Annotation of /FigKernelPackages/Tracer.pm

Parent Directory Parent Directory | Revision Log Revision Log


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

1 : olson 1.30 #
2 :     # Copyright (c) 2003-2006 University of Chicago and Fellowship
3 :     # for Interpretations of Genomes. All Rights Reserved.
4 :     #
5 :     # This file is part of the SEED Toolkit.
6 : parrello 1.61 #
7 : olson 1.30 # The SEED Toolkit is free software. You can redistribute
8 :     # it and/or modify it under the terms of the SEED Toolkit
9 : parrello 1.61 # Public License.
10 : olson 1.30 #
11 :     # You should have received a copy of the SEED Toolkit Public License
12 :     # along with this program; if not write to the University of Chicago
13 :     # at info@ci.uchicago.edu or the Fellowship for Interpretation of
14 :     # Genomes at veronika@thefig.info or download a copy from
15 :     # http://www.theseed.org/LICENSE.TXT.
16 :     #
17 :    
18 : olson 1.1 package Tracer;
19 :    
20 : parrello 1.12 require Exporter;
21 :     @ISA = ('Exporter');
22 : parrello 1.45 @EXPORT = qw(Trace T TSetup QTrace Confess Cluck Min Max Assert Open OpenDir TICK StandardSetup ScriptSetup ScriptFinish Insure ChDir);
23 : parrello 1.12 @EXPORT_OK = qw(GetFile GetOptions Merge MergeOptions ParseCommand ParseRecord UnEscape Escape);
24 :     use strict;
25 :     use Carp qw(longmess croak);
26 :     use CGI;
27 : parrello 1.47 use Cwd;
28 : parrello 1.12 use FIG_Config;
29 : parrello 1.9 use PageBuilder;
30 : parrello 1.21 use Digest::MD5;
31 : parrello 1.36 use File::Basename;
32 : parrello 1.37 use File::Path;
33 : parrello 1.48 use File::stat;
34 : parrello 1.59 use LWP::UserAgent;
35 : parrello 1.64 use Time::HiRes 'gettimeofday';
36 : parrello 1.65 use URI::Escape;
37 : olson 1.1
38 :     =head1 Tracing and Debugging Helpers
39 :    
40 :     =head2 Introduction
41 :    
42 :     This package provides simple tracing for debugging and reporting purposes. To use it simply call the
43 :     L</TSetup> method to set the options and call L</Trace> to write out trace messages. Each trace
44 : parrello 1.2 message has a I<trace level> and I<category> associated with it. In addition, the tracing package itself
45 :     has a list of categories and a single trace level set by the B<TSetup> method. Only messages whose trace
46 : olson 1.1 level is less than or equal to this package's trace level and whose category is activated will
47 : parrello 1.2 be written. Thus, a higher trace level on a message indicates that the message
48 : parrello 1.10 is less likely to be seen. A higher trace level passed to B<TSetup> means more trace messages will
49 : olson 1.1 appear. To generate a trace message, use the following syntax.
50 :    
51 :     C<< Trace($message) if T(errors => 4); >>
52 :    
53 : parrello 1.2 This statement will produce a trace message if the trace level is 4 or more and the C<errors>
54 : parrello 1.3 category is active. Note that the special category C<main> is always active, so
55 : olson 1.1
56 : parrello 1.3 C<< Trace($message) if T(main => 4); >>
57 : olson 1.1
58 :     will trace if the trace level is 4 or more.
59 :    
60 :     If the category name is the same as the package name, all you need is the number. So, if the
61 :     following call is made in the B<Sprout> package, it will appear if the C<Sprout> category is
62 :     active and the trace level is 2 or more.
63 :    
64 :     C<< Trace($message) if T(2); >>
65 :    
66 : parrello 1.10 To set up tracing, you call the L</TSetup> method. The method takes as input a trace level, a list
67 : olson 1.1 of category names, and a set of options. The trace level and list of category names are
68 :     specified as a space-delimited string. Thus
69 :    
70 :     C<< TSetup('3 errors Sprout ERDB', 'HTML'); >>
71 :    
72 : parrello 1.7 sets the trace level to 3, activates the C<errors>, C<Sprout>, and C<ERDB> categories, and
73 : parrello 1.12 specifies that messages should be output as HTML paragraphs.
74 :    
75 :     To turn on tracing for ALL categories, use an asterisk. The call below sets every category to
76 :     level 3 and writes the output to the standard error output. This sort of thing might be
77 :     useful in a CGI environment.
78 :    
79 :     C<< TSetup('3 *', 'WARN'); >>
80 : olson 1.1
81 :     In addition to HTML and file output for trace messages, you can specify that the trace messages
82 :     be queued. The messages can then be retrieved by calling the L</QTrace> method. This approach
83 :     is useful if you are building a web page. Instead of having the trace messages interspersed with
84 :     the page output, they can be gathered together and displayed at the end of the page. This makes
85 :     it easier to debug page formatting problems.
86 :    
87 : parrello 1.4 Finally, you can specify that all trace messages be emitted as warnings.
88 :    
89 : olson 1.1 The flexibility of tracing makes it superior to simple use of directives like C<die> and C<warn>.
90 :     Tracer calls can be left in the code with minimal overhead and then turned on only when needed.
91 :     Thus, debugging information is available and easily retrieved even when the application is
92 :     being used out in the field.
93 :    
94 : parrello 1.10 There is no hard and fast rule on how to use trace levels. The following is therefore only
95 :     a suggestion.
96 :    
97 :     =over 4
98 :    
99 : parrello 1.32 =item Error 0
100 : parrello 1.10
101 :     Message indicates an error that may lead to incorrect results or that has stopped the
102 :     application entirely.
103 :    
104 : parrello 1.32 =item Warning 1
105 : parrello 1.10
106 :     Message indicates something that is unexpected but that probably did not interfere
107 :     with program execution.
108 :    
109 : parrello 1.32 =item Notice 2
110 : parrello 1.10
111 :     Message indicates the beginning or end of a major task.
112 :    
113 : parrello 1.32 =item Information 3
114 : parrello 1.10
115 :     Message indicates a subtask. In the FIG system, a subtask generally relates to a single
116 :     genome. This would be a big loop that is not expected to execute more than 500 times or so.
117 :    
118 : parrello 1.32 =item Detail 4
119 : parrello 1.10
120 :     Message indicates a low-level loop iteration.
121 :    
122 :     =back
123 :    
124 : olson 1.1 =cut
125 : parrello 1.2
126 : olson 1.1 # Declare the configuration variables.
127 :    
128 : parrello 1.12 my $Destination = "NONE"; # Description of where to send the trace output.
129 :     my $TeeFlag = 0; # TRUE if output is going to a file and to the
130 :     # standard output
131 : parrello 1.3 my %Categories = ( main => 1 );
132 : parrello 1.12 # hash of active category names
133 :     my $TraceLevel = 0; # trace level; a higher trace level produces more
134 :     # messages
135 :     my @Queue = (); # queued list of trace messages.
136 : parrello 1.7 my $LastCategory = "main"; # name of the last category interrogated
137 : parrello 1.11 my $SetupCount = 0; # number of times TSetup called
138 : parrello 1.12 my $AllTrace = 0; # TRUE if we are tracing all categories.
139 : olson 1.1
140 :     =head2 Public Methods
141 :    
142 :     =head3 TSetup
143 :    
144 :     C<< TSetup($categoryList, $target); >>
145 :    
146 :     This method is used to specify the trace options. The options are stored as package data
147 :     and interrogated by the L</Trace> and L</T> methods.
148 :    
149 :     =over 4
150 :    
151 :     =item categoryList
152 :    
153 :     A string specifying the trace level and the categories to be traced, separated by spaces.
154 :     The trace level must come first.
155 :    
156 :     =item target
157 :    
158 :     The destination for the trace output. To send the trace output to a file, specify the file
159 :     name preceded by a ">" symbol. If a double symbol is used (">>"), then the data is appended
160 : parrello 1.10 to the file. Otherwise the file is cleared before tracing begins. Precede the first ">"
161 :     symbol with a C<+> to echo output to a file AND to the standard output. In addition to
162 :     sending the trace messages to a file, you can specify a special destination. C<HTML> will
163 :     cause tracing to the standard output with each line formatted as an HTML paragraph. C<TEXT>
164 : parrello 1.5 will cause tracing to the standard output as ordinary text. C<ERROR> will cause trace
165 : parrello 1.9 messages to be sent to the standard error output as ordinary text. C<QUEUE> will cause trace
166 : parrello 1.6 messages to be stored in a queue for later retrieval by the L</QTrace> method. C<WARN> will
167 : parrello 1.9 cause trace messages to be emitted as warnings using the B<warn> directive. C<NONE> will
168 : parrello 1.6 cause tracing to be suppressed.
169 : olson 1.1
170 :     =back
171 :    
172 :     =cut
173 :    
174 :     sub TSetup {
175 : parrello 1.12 # Get the parameters.
176 :     my ($categoryList, $target) = @_;
177 :     # Parse the category list.
178 :     my @categoryData = split /\s+/, $categoryList;
179 :     # Extract the trace level.
180 :     $TraceLevel = shift @categoryData;
181 :     # Presume category-based tracing until we learn otherwise.
182 :     $AllTrace = 0;
183 :     # Build the category hash. Note that if we find a "*", we turn on non-category
184 : parrello 1.33 # tracing. We must also clear away any pre-existing data.
185 : parrello 1.34 %Categories = ( main => 1 );
186 : parrello 1.12 for my $category (@categoryData) {
187 :     if ($category eq '*') {
188 :     $AllTrace = 1;
189 :     } else {
190 : parrello 1.13 $Categories{lc $category} = 1;
191 : parrello 1.12 }
192 :     }
193 :     # Now we need to process the destination information. The most important special
194 :     # cases are the single ">", which requires we clear the file first, and the
195 :     # "+" prefix which indicates a double echo.
196 :     if ($target =~ m/^\+?>>?/) {
197 :     if ($target =~ m/^\+/) {
198 :     $TeeFlag = 1;
199 :     $target = substr($target, 1);
200 :     }
201 :     if ($target =~ m/^>[^>]/) {
202 :     open TRACEFILE, $target;
203 :     print TRACEFILE Now() . " Tracing initialized.\n";
204 :     close TRACEFILE;
205 :     $Destination = ">$target";
206 :     } else {
207 :     $Destination = $target;
208 :     }
209 :     } else {
210 :     $Destination = uc($target);
211 :     }
212 :     # Increment the setup counter.
213 :     $SetupCount++;
214 : parrello 1.11 }
215 :    
216 : parrello 1.31 =head3 StandardSetup
217 :    
218 : parrello 1.36 C<< my ($options, @parameters) = StandardSetup(\@categories, \%options, $parmHelp, @ARGV); >>
219 : parrello 1.31
220 :     This method performs standard command-line parsing and tracing setup. The return
221 :     values are a hash of the command-line options and a list of the positional
222 :     parameters. Tracing is automatically set up and the command-line options are
223 :     validated.
224 :    
225 :     This is a complex method that does a lot of grunt work. The parameters can
226 :     be more easily understood, however, once they are examined individually.
227 :    
228 :     The I<categories> parameter is the most obtuse. It is a reference to a list of
229 :     special-purpose tracing categories. Most tracing categories are PERL package
230 :     names. So, for example, if you wanted to turn on tracing inside the B<Sprout>,
231 :     B<ERDB>, and B<SproutLoad> packages, you would specify the categories
232 :    
233 :     ["Sprout", "SproutLoad", "ERDB"]
234 :    
235 :     This would cause trace messages in the specified three packages to appear in
236 :     the output. There are threer special tracing categories that are automatically
237 :     handled by this method. In other words, if you used L</TSetup> you would need
238 :     to include these categories manually, but if you use this method they are turned
239 :     on automatically.
240 :    
241 :     =over 4
242 :    
243 :     =item FIG
244 :    
245 :     Turns on trace messages inside the B<FIG> package.
246 :    
247 :     =item SQL
248 :    
249 :     Traces SQL commands and activity.
250 :    
251 :     =item Tracer
252 :    
253 :     Traces error messages and call stacks.
254 :    
255 :     =back
256 :    
257 :     C<SQL> is only turned on if the C<-sql> option is specified in the command line.
258 :     The trace level is specified using the C<-trace> command-line option. For example,
259 :     the following command line for C<TransactFeatures> turns on SQL tracing and runs
260 :     all tracing at level 3.
261 :    
262 :     TransactFeatures -trace=3 -sql register ../xacts IDs.tbl
263 :    
264 :     Standard tracing is output to the standard output and echoed to the file
265 : parrello 1.38 C<trace>I<$$>C<.log> in the FIG temporary directory, where I<$$> is the
266 :     process ID. You can also specify the C<user> parameter to put a user ID
267 :     instead of a process ID in the trace file name. So, for example
268 : parrello 1.31
269 : parrello 1.35 The default trace level is 2. To get all messages, specify a trace level of 4.
270 :     For a genome-by-genome update, use 3.
271 : parrello 1.31
272 : parrello 1.38 TransactFeatures -trace=3 -sql -user=Bruce register ../xacts IDs.tbl
273 :    
274 :     would send the trace output to C<traceBruce.log> in the temporary directory.
275 :    
276 : parrello 1.31 The I<options> parameter is a reference to a hash containing the command-line
277 : parrello 1.36 options, their default values, and an explanation of what they mean. Command-line
278 :     options may be in the form of switches or keywords. In the case of a switch, the
279 :     option value is 1 if it is specified and 0 if it is not specified. In the case
280 :     of a keyword, the value is separated from the option name by an equal sign. You
281 :     can see this last in the command-line example above.
282 : parrello 1.31
283 : parrello 1.42 You can specify a different default trace level by setting C<$options->{trace}>
284 :     prior to calling this method.
285 :    
286 : parrello 1.31 An example at this point would help. Consider, for example, the command-line utility
287 :     C<TransactFeatures>. It accepts a list of positional parameters plus the options
288 :     C<safe>, C<noAlias>, C<start>, and C<tblFiles>. To start up this command, we execute
289 :     the following code.
290 :    
291 :     my ($options, @parameters) = Tracer::StandardSetup(["DocUtils"],
292 : parrello 1.36 { safe => [0, "use database transactions"],
293 :     noAlias => [0, "do not expect aliases in CHANGE transactions"],
294 :     start => [' ', "start with this genome"],
295 :     tblFiles => [0, "output TBL files containing the corrected IDs"] },
296 :     "command transactionDirectory IDfile",
297 :     @ARGV);
298 : parrello 1.31
299 :    
300 :     The call to C<ParseCommand> specifies the default values for the options and
301 :     stores the actual options in a hash that is returned as C<$options>. The
302 : parrello 1.61 positional parameters are returned in C<@parameters>.
303 : parrello 1.31
304 :     The following is a sample command line for C<TransactFeatures>.
305 :    
306 :     TransactFeatures -trace=2 -noAlias register ../xacts IDs.tbl
307 :    
308 :     In this case, C<register>, C<../xacts>, and C<IDs.tbl> are the positional
309 :     parameters, and would find themselves in I<@parameters> after executing the
310 :     above code fragment. The tracing would be set to level 2, and the categories
311 :     would be C<FIG>, C<Tracer>, and <DocUtils>. C<FIG> and C<Tracer> are standard,
312 :     and C<DocUtils> was included because it came in within the first parameter
313 :     to this method. The I<$options> hash would be
314 :    
315 :     { trace => 2, sql => 0, safe => 0,
316 :     noAlias => 1, start => ' ', tblFiles => 0 }
317 :    
318 :     Use of C<StandardSetup> in this way provides a simple way of performing
319 :     standard tracing setup and command-line parsing. Note that the caller is
320 :     not even aware of the command-line switches C<-trace> and C<-sql>, which
321 :     are used by this method to control the tracing. If additional tracing features
322 :     need to be added in the future, they can be processed by this method without
323 :     upsetting the command-line utilities.
324 :    
325 : parrello 1.42 If the C<background> option is specified on the command line, then the
326 :     standard and error outputs will be directed to files in the temporary
327 :     directory, using the same suffix as the trace file. So, if the command
328 :     line specified
329 :    
330 :     -user=Bruce -background
331 :    
332 :     then the trace output would go to C<traceBruce.log>, the standard output to
333 :     C<outBruce.log>, and the error output to C<errBruce.log>. This is designed to
334 :     simplify starting a command in the background.
335 :    
336 : parrello 1.36 Finally, if the special option C<-h> is specified, the option names will
337 :     be traced at level 0 and the program will exit without processing.
338 :     This provides a limited help capability. For example, if the user enters
339 :    
340 :     TransactFeatures -h
341 :    
342 :     he would see the following output.
343 :    
344 :     TransactFeatures [options] command transactionDirectory IDfile
345 :     -trace tracing level (default 2)
346 :     -sql trace SQL commands
347 :     -safe use database transactions
348 :     -noAlias do not expect aliases in CHANGE transactions
349 :     -start start with this genome
350 :     -tblFiles output TBL files containing the corrected IDs
351 :    
352 : parrello 1.44 The caller has the option of modifying the tracing scheme by placing a value
353 :     for C<trace> in the incoming options hash. The default value can be overridden,
354 :     or the tracing to the standard output can be turned off by suffixing a minus
355 : parrello 1.61 sign to the trace level. So, for example,
356 : parrello 1.44
357 :     { trace => [0, "tracing level (default 0)"],
358 :     ...
359 :    
360 :     would set the default trace level to 0 instead of 2, while
361 :    
362 :     { trace => ["2-", "tracing level (default 2)"],
363 :     ...
364 :    
365 :     would leave the default at 2, but trace only to the log file, not to the
366 :     standard output.
367 :    
368 : parrello 1.31 The parameters to this method are as follows.
369 :    
370 :     =over 4
371 :    
372 :     =item categories
373 :    
374 :     Reference to a list of tracing category names. These should be names of
375 :     packages whose internal workings will need to be debugged to get the
376 :     command working.
377 :    
378 :     =item options
379 :    
380 :     Reference to a hash containing the legal options for the current command mapped
381 : parrello 1.36 to their default values and descriptions. The user can override the defaults
382 :     by specifying the options as command-line switches prefixed by a hyphen.
383 :     Tracing-related options may be added to this hash. If the C<-h> option is
384 :     specified on the command line, the option descriptions will be used to
385 : parrello 1.44 explain the options. To turn off tracing to the standard output, add a
386 :     minus sign to the value for C<trace> (see above).
387 : parrello 1.36
388 :     =item parmHelp
389 :    
390 :     A string that vaguely describes the positional parameters. This is used
391 :     if the user specifies the C<-h> option.
392 : parrello 1.31
393 : parrello 1.44 =item argv
394 : parrello 1.31
395 :     List of command line parameters, including the option switches, which must
396 :     precede the positional parameters and be prefixed by a hyphen.
397 :    
398 :     =item RETURN
399 :    
400 :     Returns a list. The first element of the list is the reference to a hash that
401 :     maps the command-line option switches to their values. These will either be the
402 :     default values or overrides specified on the command line. The remaining
403 :     elements of the list are the position parameters, in order.
404 :    
405 :     =back
406 :    
407 :     =cut
408 :    
409 :     sub StandardSetup {
410 :     # Get the parameters.
411 : parrello 1.36 my ($categories, $options, $parmHelp, @argv) = @_;
412 : parrello 1.31 # Add the tracing options.
413 : parrello 1.41 if (! exists $options->{trace}) {
414 :     $options->{trace} = [2, "tracing level"];
415 :     }
416 : parrello 1.36 $options->{sql} = [0, "turn on SQL tracing"];
417 :     $options->{h} = [0, "display command-line options"];
418 : parrello 1.38 $options->{user} = [$$, "trace log file name suffix"];
419 : parrello 1.42 $options->{background} = [0, "spool standard and error output"];
420 : parrello 1.36 # Create a parsing hash from the options hash. The parsing hash
421 :     # contains the default values rather than the default value
422 :     # and the description. While we're at it, we'll memorize the
423 :     # length of the longest option name.
424 :     my $longestName = 0;
425 :     my %parseOptions = ();
426 :     for my $key (keys %{$options}) {
427 :     if (length $key > $longestName) {
428 :     $longestName = length $key;
429 :     }
430 :     $parseOptions{$key} = $options->{$key}->[0];
431 :     }
432 : parrello 1.31 # Parse the command line.
433 : parrello 1.36 my ($retOptions, @retParameters) = ParseCommand(\%parseOptions, @argv);
434 : parrello 1.42 # Get the logfile suffix.
435 :     my $suffix = $retOptions->{user};
436 :     # Check for background mode.
437 :     if ($retOptions->{background}) {
438 :     my $outFileName = "$FIG_Config::temp/out$suffix.log";
439 :     my $errFileName = "$FIG_Config::temp/err$suffix.log";
440 :     open STDOUT, ">$outFileName";
441 :     open STDERR, ">$errFileName";
442 :     }
443 : parrello 1.31 # Now we want to set up tracing. First, we need to know if SQL is to
444 :     # be traced.
445 :     my @cats = @{$categories};
446 :     if ($retOptions->{sql}) {
447 :     push @cats, "SQL";
448 :     }
449 :     # Add the default categories.
450 :     push @cats, "Tracer", "FIG";
451 : parrello 1.44 # Next, we create the category string by joining the categories.
452 :     my $cats = join(" ", @cats);
453 :     # Check to determine whether or not the caller wants to turn off tracing
454 :     # to the standard output.
455 :     my $traceLevel = $retOptions->{trace};
456 :     my $textOKFlag = 1;
457 :     if ($traceLevel =~ /^(.)-/) {
458 :     $traceLevel = $1;
459 :     $textOKFlag = 0;
460 :     }
461 :     # Now we set up the trace mode.
462 :     my $traceMode;
463 :     # Verify that we can open a file in the FIG temporary directory.
464 : parrello 1.40 my $traceFileName = "$FIG_Config::temp/trace$suffix.log";
465 :     if (open TESTTRACE, ">$traceFileName") {
466 : parrello 1.44 # Here we can trace to a file.
467 :     $traceMode = ">$traceFileName";
468 :     if ($textOKFlag) {
469 :     # Echo to standard output if the text-OK flag is set.
470 :     $traceMode = "+$traceMode";
471 :     }
472 :     # Close the test file.
473 : parrello 1.40 close TESTTRACE;
474 : parrello 1.44 } else {
475 :     # Here we can't trace to a file. We trace to the standard output if it's
476 :     # okay, and the error log otherwise.
477 :     if ($textOKFlag) {
478 :     $traceMode = "TEXT";
479 :     } else {
480 :     $traceMode = "WARN";
481 :     }
482 : parrello 1.40 }
483 : parrello 1.31 # Now set up the tracing.
484 : parrello 1.44 TSetup("$traceLevel $cats", $traceMode);
485 : parrello 1.36 # Check for the "h" option. If it is specified, dump the command-line
486 :     # options and exit the program.
487 :     if ($retOptions->{h}) {
488 :     $0 =~ m#[/\\](\w+)(\.pl)?$#i;
489 :     Trace("$1 [options] $parmHelp") if T(0);
490 :     for my $key (sort keys %{$options}) {
491 :     my $name = Pad($key, $longestName, 0, ' ');
492 :     my $desc = $options->{$key}->[1];
493 :     if ($options->{$key}->[0]) {
494 :     $desc .= " (default " . $options->{$key}->[0] . ")";
495 :     }
496 :     Trace(" $name $desc") if T(0);
497 :     }
498 :     exit(0);
499 :     }
500 : parrello 1.31 # Return the parsed parameters.
501 :     return ($retOptions, @retParameters);
502 :     }
503 :    
504 : parrello 1.11 =head3 Setups
505 :    
506 :     C<< my $count = Tracer::Setups(); >>
507 :    
508 :     Return the number of times L</TSetup> has been called.
509 :    
510 :     This method allows for the creation of conditional tracing setups where, for example, we
511 :     may want to set up tracing if nobody else has done it before us.
512 :    
513 :     =cut
514 :    
515 :     sub Setups {
516 : parrello 1.12 return $SetupCount;
517 : olson 1.1 }
518 :    
519 : parrello 1.10 =head3 Open
520 :    
521 :     C<< my $handle = Open($fileHandle, $fileSpec, $message); >>
522 :    
523 : parrello 1.11 Open a file.
524 : parrello 1.10
525 :     The I<$fileSpec> is essentially the second argument of the PERL C<open>
526 :     function. The mode is specified using Unix-like shell information. So, for
527 :     example,
528 :    
529 : parrello 1.12 Open(\*LOGFILE, '>>/usr/spool/news/twitlog', "Could not open twit log.");
530 : parrello 1.10
531 :     would open for output appended to the specified file, and
532 :    
533 : parrello 1.12 Open(\*DATASTREAM, "| sort -u >$outputFile", "Could not open $outputFile.");
534 : parrello 1.10
535 :     would open a pipe that sorts the records written and removes duplicates. Note
536 : parrello 1.11 the use of file handle syntax in the Open call. To use anonymous file handles,
537 :     code as follows.
538 : parrello 1.10
539 : parrello 1.12 my $logFile = Open(undef, '>>/usr/spool/news/twitlog', "Could not open twit log.");
540 : parrello 1.10
541 : parrello 1.11 The I<$message> parameter is used if the open fails. If it is set to C<0>, then
542 :     the open returns TRUE if successful and FALSE if an error occurred. Otherwise, a
543 :     failed open will throw an exception and the third parameter will be used to construct
544 :     an error message. If the parameter is omitted, a standard message is constructed
545 :     using the file spec.
546 : parrello 1.10
547 : parrello 1.12 Could not open "/usr/spool/news/twitlog"
548 : parrello 1.10
549 :     Note that the mode characters are automatically cleaned from the file name.
550 :     The actual error message from the file system will be captured and appended to the
551 :     message in any case.
552 :    
553 : parrello 1.12 Could not open "/usr/spool/news/twitlog": file not found.
554 : parrello 1.10
555 :     In some versions of PERL the only error message we get is a number, which
556 :     corresponds to the C++ C<errno> value.
557 :    
558 : parrello 1.12 Could not open "/usr/spool/news/twitlog": 6.
559 : parrello 1.10
560 :     =over 4
561 :    
562 :     =item fileHandle
563 :    
564 :     File handle. If this parameter is C<undef>, a file handle will be generated
565 :     and returned as the value of this method.
566 :    
567 :     =item fileSpec
568 :    
569 :     File name and mode, as per the PERL C<open> function.
570 :    
571 :     =item message (optional)
572 :    
573 :     Error message to use if the open fails. If omitted, a standard error message
574 :     will be generated. In either case, the error information from the file system
575 : parrello 1.11 is appended to the message. To specify a conditional open that does not throw
576 :     an error if it fails, use C<0>.
577 : parrello 1.10
578 :     =item RETURN
579 :    
580 : parrello 1.11 Returns the name of the file handle assigned to the file, or C<undef> if the
581 :     open failed.
582 : parrello 1.10
583 :     =back
584 :    
585 :     =cut
586 :    
587 :     sub Open {
588 : parrello 1.12 # Get the parameters.
589 :     my ($fileHandle, $fileSpec, $message) = @_;
590 :     # Attempt to open the file.
591 :     my $rv = open $fileHandle, $fileSpec;
592 :     # If the open failed, generate an error message.
593 :     if (! $rv) {
594 :     # Save the system error message.
595 :     my $sysMessage = $!;
596 :     # See if we need a default message.
597 :     if (!$message) {
598 :     # Clean any obvious mode characters and leading spaces from the
599 :     # filename.
600 :     my ($fileName) = FindNamePart($fileSpec);
601 :     $message = "Could not open \"$fileName\"";
602 :     }
603 :     # Terminate with an error using the supplied message and the
604 :     # error message from the file system.
605 :     Confess("$message: $!");
606 :     }
607 :     # Return the file handle.
608 :     return $fileHandle;
609 : parrello 1.10 }
610 :    
611 : parrello 1.11 =head3 FindNamePart
612 :    
613 :     C<< my ($fileName, $start, $len) = Tracer::FindNamePart($fileSpec); >>
614 :    
615 :     Extract the portion of a file specification that contains the file name.
616 :    
617 :     A file specification is the string passed to an C<open> call. It specifies the file
618 :     mode and name. In a truly complex situation, it can specify a pipe sequence. This
619 :     method assumes that the file name is whatever follows the first angle bracket
620 :     sequence. So, for example, in the following strings the file name is
621 :     C</usr/fig/myfile.txt>.
622 :    
623 :     >>/usr/fig/myfile.txt
624 :     </usr/fig/myfile.txt
625 :     | sort -u > /usr/fig/myfile.txt
626 :    
627 :     If the method cannot find a file name using its normal methods, it will return the
628 :     whole incoming string.
629 :    
630 :     =over 4
631 :    
632 :     =item fileSpec
633 :    
634 :     File specification string from which the file name is to be extracted.
635 :    
636 :     =item RETURN
637 :    
638 :     Returns a three-element list. The first element contains the file name portion of
639 :     the specified string, or the whole string if a file name cannot be found via normal
640 :     methods. The second element contains the start position of the file name portion and
641 :     the third element contains the length.
642 :    
643 :     =back
644 :    
645 :     =cut
646 :     #: Return Type $;
647 :     sub FindNamePart {
648 :     # Get the parameters.
649 :     my ($fileSpec) = @_;
650 : parrello 1.12 # Default to the whole input string.
651 :     my ($retVal, $pos, $len) = ($fileSpec, 0, length $fileSpec);
652 : parrello 1.11 # Parse out the file name if we can.
653 : parrello 1.12 if ($fileSpec =~ m/(<|>>?)(.+?)(\s*)$/) {
654 :     $retVal = $2;
655 :     $len = length $retVal;
656 :     $pos = (length $fileSpec) - (length $3) - $len;
657 :     }
658 : parrello 1.11 # Return the result.
659 :     return ($retVal, $pos, $len);
660 :     }
661 :    
662 :     =head3 OpenDir
663 :    
664 : parrello 1.31 C<< my @files = OpenDir($dirName, $filtered, $flag); >>
665 : parrello 1.11
666 :     Open a directory and return all the file names. This function essentially performs
667 :     the functions of an C<opendir> and C<readdir>. If the I<$filtered> parameter is
668 : parrello 1.31 set to TRUE, all filenames beginning with a period (C<.>), dollar sign (C<$>),
669 : parrello 1.33 or pound sign (C<#>) and all filenames ending with a tilde C<~>) will be
670 :     filtered out of the return list. If the directory does not open and I<$flag> is not
671 :     set, an exception is thrown. So, for example,
672 : parrello 1.11
673 : parrello 1.12 my @files = OpenDir("/Volumes/fig/contigs", 1);
674 : parrello 1.29
675 : parrello 1.11 is effectively the same as
676 :    
677 : parrello 1.12 opendir(TMP, "/Volumes/fig/contigs") || Confess("Could not open /Volumes/fig/contigs.");
678 : parrello 1.33 my @files = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir(TMP);
679 : parrello 1.11
680 :     Similarly, the following code
681 :    
682 : parrello 1.31 my @files = grep { $_ =~ /^\d/ } OpenDir("/Volumes/fig/orgs", 0, 1);
683 : parrello 1.29
684 : parrello 1.11 Returns the names of all files in C</Volumes/fig/orgs> that begin with digits and
685 : parrello 1.31 automatically returns an empty list if the directory fails to open.
686 : parrello 1.11
687 :     =over 4
688 :    
689 :     =item dirName
690 :    
691 :     Name of the directory to open.
692 :    
693 :     =item filtered
694 :    
695 :     TRUE if files whose names begin with a period (C<.>) should be automatically removed
696 :     from the list, else FALSE.
697 :    
698 : parrello 1.31 =item flag
699 :    
700 :     TRUE if a failure to open is okay, else FALSE
701 :    
702 : parrello 1.11 =back
703 :    
704 :     =cut
705 :     #: Return Type @;
706 :     sub OpenDir {
707 :     # Get the parameters.
708 : parrello 1.31 my ($dirName, $filtered, $flag) = @_;
709 : parrello 1.11 # Declare the return variable.
710 : parrello 1.31 my @retVal = ();
711 : parrello 1.12 # Open the directory.
712 :     if (opendir(my $dirHandle, $dirName)) {
713 :     # The directory opened successfully. Get the appropriate list according to the
714 :     # strictures of the filter parameter.
715 :     if ($filtered) {
716 : parrello 1.33 @retVal = grep { $_ !~ /^[\.\$\#]/ && $_ !~ /~$/ } readdir $dirHandle;
717 : parrello 1.12 } else {
718 :     @retVal = readdir $dirHandle;
719 :     }
720 : parrello 1.31 } elsif (! $flag) {
721 :     # Here the directory would not open and it's considered an error.
722 : parrello 1.12 Confess("Could not open directory $dirName.");
723 :     }
724 : parrello 1.11 # Return the result.
725 :     return @retVal;
726 :     }
727 :    
728 : parrello 1.6 =head3 SetLevel
729 :    
730 :     C<< Tracer::SetLevel($newLevel); >>
731 :    
732 :     Modify the trace level. A higher trace level will cause more messages to appear.
733 :    
734 :     =over 4
735 :    
736 :     =item newLevel
737 :    
738 :     Proposed new trace level.
739 :    
740 :     =back
741 :    
742 :     =cut
743 :    
744 :     sub SetLevel {
745 :     $TraceLevel = $_[0];
746 :     }
747 :    
748 : olson 1.1 =head3 Now
749 :    
750 :     C<< my $string = Tracer::Now(); >>
751 :    
752 :     Return a displayable time stamp containing the local time.
753 :    
754 :     =cut
755 :    
756 :     sub Now {
757 : parrello 1.12 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
758 :     my $retVal = _p2($mon+1) . "/" . _p2($mday) . "/" . ($year + 1900) . " " .
759 :     _p2($hour) . ":" . _p2($min) . ":" . _p2($sec);
760 :     return $retVal;
761 : olson 1.1 }
762 :    
763 :     # Pad a number to 2 digits.
764 :     sub _p2 {
765 : parrello 1.12 my ($value) = @_;
766 :     $value = "0$value" if ($value < 10);
767 :     return $value;
768 : olson 1.1 }
769 :    
770 :     =head3 LogErrors
771 :    
772 :     C<< Tracer::LogErrors($fileName); >>
773 :    
774 :     Route the standard error output to a log file.
775 :    
776 :     =over 4
777 :    
778 :     =item fileName
779 :    
780 :     Name of the file to receive the error output.
781 :    
782 :     =back
783 :    
784 :     =cut
785 :    
786 :     sub LogErrors {
787 : parrello 1.12 # Get the file name.
788 :     my ($fileName) = @_;
789 :     # Open the file as the standard error output.
790 :     open STDERR, '>', $fileName;
791 : olson 1.1 }
792 :    
793 : parrello 1.5 =head3 ReadOptions
794 :    
795 :     C<< my %options = Tracer::ReadOptions($fileName); >>
796 :    
797 :     Read a set of options from a file. Each option is encoded in a line of text that has the
798 :     format
799 :    
800 :     I<optionName>C<=>I<optionValue>C<; >I<comment>
801 :    
802 :     The option name must consist entirely of letters, digits, and the punctuation characters
803 : parrello 1.9 C<.> and C<_>, and is case sensitive. Blank lines and lines in which the first nonblank
804 :     character is a semi-colon will be ignored. The return hash will map each option name to
805 : parrello 1.5 the corresponding option value.
806 :    
807 :     =over 4
808 :    
809 :     =item fileName
810 :    
811 :     Name of the file containing the option data.
812 :    
813 :     =item RETURN
814 :    
815 :     Returns a hash mapping the option names specified in the file to their corresponding option
816 :     value.
817 :    
818 :     =back
819 :    
820 :     =cut
821 :    
822 :     sub ReadOptions {
823 : parrello 1.12 # Get the parameters.
824 :     my ($fileName) = @_;
825 :     # Open the file.
826 :     (open CONFIGFILE, "<$fileName") || Confess("Could not open option file $fileName.");
827 :     # Count the number of records read.
828 :     my ($records, $comments) = 0;
829 :     # Create the return hash.
830 :     my %retVal = ();
831 :     # Loop through the file, accumulating key-value pairs.
832 :     while (my $line = <CONFIGFILE>) {
833 :     # Denote we've read a line.
834 :     $records++;
835 :     # Determine the line type.
836 :     if ($line =~ /^\s*[\n\r]/) {
837 :     # A blank line is a comment.
838 :     $comments++;
839 :     } elsif ($line =~ /^\s*([A-Za-z0-9_\.]+)=([^;]*);/) {
840 :     # Here we have an option assignment.
841 :     retVal{$1} = $2;
842 :     } elsif ($line =~ /^\s*;/) {
843 :     # Here we have a text comment.
844 :     $comments++;
845 :     } else {
846 :     # Here we have an invalid line.
847 :     Trace("Invalid option statement in record $records.") if T(0);
848 :     }
849 :     }
850 :     # Return the hash created.
851 :     return %retVal;
852 : parrello 1.5 }
853 :    
854 : olson 1.1 =head3 GetOptions
855 :    
856 :     C<< Tracer::GetOptions(\%defaults, \%options); >>
857 :    
858 :     Merge a specified set of options into a table of defaults. This method takes two hash references
859 :     as input and uses the data from the second to update the first. If the second does not exist,
860 :     there will be no effect. An error will be thrown if one of the entries in the second hash does not
861 :     exist in the first.
862 :    
863 :     Consider the following example.
864 :    
865 :     C<< my $optionTable = GetOptions({ dbType => 'mySQL', trace => 0 }, $options); >>
866 :    
867 :     In this example, the variable B<$options> is expected to contain at most two options-- B<dbType> and
868 :     B<trace>. The default database type is C<mySQL> and the default trace level is C<0>. If the value of
869 :     B<$options> is C<< {dbType => 'Oracle'} >>, then the database type will be changed to C<Oracle> and
870 :     the trace level will remain at 0. If B<$options> is undefined, then the database type and trace level
871 :     will remain C<mySQL> and C<0>. If, on the other hand, B<$options> is defined as
872 :    
873 :     C<< {databaseType => 'Oracle'} >>
874 :    
875 :     an error will occur because the B<databaseType> option does not exist.
876 :    
877 :     =over 4
878 :    
879 :     =item defaults
880 :    
881 :     Table of default option values.
882 :    
883 :     =item options
884 :    
885 :     Table of overrides, if any.
886 :    
887 :     =item RETURN
888 :    
889 :     Returns a reference to the default table passed in as the first parameter.
890 :    
891 :     =back
892 :    
893 :     =cut
894 :    
895 :     sub GetOptions {
896 : parrello 1.12 # Get the parameters.
897 :     my ($defaults, $options) = @_;
898 :     # Check for overrides.
899 :     if ($options) {
900 :     # Loop through the overrides.
901 :     while (my ($option, $setting) = each %{$options}) {
902 :     # Insure this override exists.
903 :     if (!exists $defaults->{$option}) {
904 :     croak "Unrecognized option $option encountered.";
905 :     } else {
906 :     # Apply the override.
907 :     $defaults->{$option} = $setting;
908 :     }
909 :     }
910 :     }
911 :     # Return the merged table.
912 :     return $defaults;
913 : olson 1.1 }
914 :    
915 :     =head3 MergeOptions
916 :    
917 :     C<< Tracer::MergeOptions(\%table, \%defaults); >>
918 :    
919 :     Merge default values into a hash table. This method looks at the key-value pairs in the
920 :     second (default) hash, and if a matching key is not found in the first hash, the default
921 :     pair is copied in. The process is similar to L</GetOptions>, but there is no error-
922 :     checking and no return value.
923 :    
924 :     =over 4
925 :    
926 :     =item table
927 :    
928 :     Hash table to be updated with the default values.
929 :    
930 :     =item defaults
931 :    
932 :     Default values to be merged into the first hash table if they are not already present.
933 :    
934 :     =back
935 :    
936 :     =cut
937 :    
938 :     sub MergeOptions {
939 : parrello 1.12 # Get the parameters.
940 :     my ($table, $defaults) = @_;
941 :     # Loop through the defaults.
942 :     while (my ($key, $value) = each %{$defaults}) {
943 :     if (!exists $table->{$key}) {
944 :     $table->{$key} = $value;
945 :     }
946 :     }
947 : olson 1.1 }
948 :    
949 :     =head3 Trace
950 :    
951 :     C<< Trace($message); >>
952 :    
953 :     Write a trace message to the target location specified in L</TSetup>. If there has not been
954 :     any prior call to B<TSetup>.
955 :    
956 :     =over 4
957 :    
958 :     =item message
959 :    
960 :     Message to write.
961 :    
962 :     =back
963 :    
964 :     =cut
965 :    
966 :     sub Trace {
967 : parrello 1.12 # Get the parameters.
968 :     my ($message) = @_;
969 :     # Get the timestamp.
970 :     my $timeStamp = Now();
971 :     # Format the message. Note we strip off any line terminators at the end.
972 :     my $formatted = "$timeStamp <$LastCategory>: " . Strip($message);
973 :     # Process according to the destination.
974 :     if ($Destination eq "TEXT") {
975 :     # Write the message to the standard output.
976 :     print "$formatted\n";
977 :     } elsif ($Destination eq "ERROR") {
978 :     # Write the message to the error output.
979 :     print STDERR "$formatted\n";
980 :     } elsif ($Destination eq "QUEUE") {
981 :     # Push the message into the queue.
982 :     push @Queue, "$formatted";
983 :     } elsif ($Destination eq "HTML") {
984 :     # Convert the message to HTML and write it to the standard output.
985 :     my $escapedMessage = CGI::escapeHTML($message);
986 :     print "<p>$formatted</p>\n";
987 : parrello 1.4 } elsif ($Destination eq "WARN") {
988 :     # Emit the message as a warning.
989 :     warn $message;
990 : parrello 1.12 } elsif ($Destination =~ m/^>>/) {
991 :     # Write the trace message to an output file.
992 : parrello 1.14 (open TRACING, $Destination) || die "Tracing open for \"$Destination\" failed: $!";
993 : parrello 1.12 print TRACING "$formatted\n";
994 :     close TRACING;
995 :     # If the Tee flag is on, echo it to the standard output.
996 :     if ($TeeFlag) {
997 :     print "$formatted\n";
998 :     }
999 :     }
1000 : olson 1.1 }
1001 :    
1002 :     =head3 T
1003 :    
1004 : parrello 1.2 C<< my $switch = T($category, $traceLevel); >>
1005 : olson 1.1
1006 : parrello 1.12 or
1007 : parrello 1.2
1008 : olson 1.1 C<< my $switch = T($traceLevel); >>
1009 :    
1010 :     Return TRUE if the trace level is at or above a specified value and the specified category
1011 :     is active, else FALSE. If no category is specified, the caller's package name is used.
1012 :    
1013 :     =over 4
1014 :    
1015 :     =item category
1016 :    
1017 :     Category to which the message belongs. If not specified, the caller's package name is
1018 :     used.
1019 :    
1020 :     =item traceLevel
1021 :    
1022 :     Relevant tracing level.
1023 :    
1024 :     =item RETURN
1025 :    
1026 :     TRUE if a message at the specified trace level would appear in the trace, else FALSE.
1027 :    
1028 :     =back
1029 :    
1030 :     =cut
1031 :    
1032 :     sub T {
1033 : parrello 1.12 # Declare the return variable.
1034 :     my $retVal = 0;
1035 :     # Only proceed if tracing is turned on.
1036 :     if ($Destination ne "NONE") {
1037 :     # Get the parameters.
1038 :     my ($category, $traceLevel) = @_;
1039 :     if (!defined $traceLevel) {
1040 :     # Here we have no category, so we need to get the calling package.
1041 :     # The calling package is normally the first parameter. If it is
1042 :     # omitted, the first parameter will be the tracelevel. So, the
1043 :     # first thing we do is shift the so-called category into the
1044 :     # $traceLevel variable where it belongs.
1045 :     $traceLevel = $category;
1046 :     my ($package, $fileName, $line) = caller;
1047 : parrello 1.3 # If there is no calling package, we default to "main".
1048 : parrello 1.12 if (!$package) {
1049 : parrello 1.3 $category = "main";
1050 : parrello 1.12 } else {
1051 :     $category = $package;
1052 :     }
1053 :     }
1054 : parrello 1.7 # Save the category name.
1055 :     $LastCategory = $category;
1056 : parrello 1.13 # Convert it to lower case before we hash it.
1057 :     $category = lc $category;
1058 : parrello 1.12 # Use the category and tracelevel to compute the result.
1059 : parrello 1.36 if (ref $traceLevel) {
1060 :     Confess("Bad trace level.");
1061 :     } elsif (ref $TraceLevel) {
1062 :     Confess("Bad trace config.");
1063 :     }
1064 : parrello 1.12 $retVal = ($traceLevel <= $TraceLevel && ($AllTrace || exists $Categories{$category}));
1065 : parrello 1.3 }
1066 : parrello 1.12 # Return the computed result.
1067 : parrello 1.3 return $retVal;
1068 : olson 1.1 }
1069 :    
1070 :     =head3 ParseCommand
1071 :    
1072 :     C<< my ($options, @arguments) = Tracer::ParseCommand(\%optionTable, @inputList); >>
1073 :    
1074 :     Parse a command line consisting of a list of parameters. The initial parameters may be option
1075 : parrello 1.2 specifiers of the form C<->I<option> or C<->I<option>C<=>I<value>. The options are stripped
1076 :     off and merged into a table of default options. The remainder of the command line is
1077 : olson 1.1 returned as a list of positional arguments. For example, consider the following invocation.
1078 :    
1079 :     C<< my ($options, @arguments) = ParseCommand({ errors => 0, logFile => 'trace.log'}, @words); >>
1080 :    
1081 :     In this case, the list @words will be treated as a command line. There are two options available,
1082 :     B<errors> and B<logFile>. If @words has the following format
1083 :    
1084 :     C<< -logFile=error.log apple orange rutabaga >>
1085 :    
1086 :     then at the end of the invocation, C<$options> will be
1087 :    
1088 :     C<< { errors => 0, logFile => 'error.log' } >>
1089 :    
1090 :     and C<@arguments> will contain
1091 :    
1092 :     C<< apple orange rutabaga >>
1093 :    
1094 : parrello 1.2 The parser allows for some escape sequences. See L</UnEscape> for a description. There is no
1095 : olson 1.1 support for quote characters.
1096 :    
1097 :     =over 4
1098 :    
1099 :     =item optionTable
1100 :    
1101 :     Table of default options.
1102 :    
1103 :     =item inputList
1104 :    
1105 :     List of words on the command line.
1106 :    
1107 :     =item RETURN
1108 :    
1109 :     Returns a reference to the option table and a list of the positional arguments.
1110 :    
1111 :     =back
1112 :    
1113 :     =cut
1114 :    
1115 :     sub ParseCommand {
1116 : parrello 1.12 # Get the parameters.
1117 :     my ($optionTable, @inputList) = @_;
1118 :     # Process any options in the input list.
1119 :     my %overrides = ();
1120 :     while ((@inputList > 0) && ($inputList[0] =~ /^-/)) {
1121 :     # Get the current option.
1122 :     my $arg = shift @inputList;
1123 :     # Pull out the option name.
1124 :     $arg =~ /^-([^=]*)/g;
1125 :     my $name = $1;
1126 :     # Check for an option value.
1127 :     if ($arg =~ /\G=(.*)$/g) {
1128 :     # Here we have a value for the option.
1129 :     $overrides{$name} = UnEscape($1);
1130 :     } else {
1131 :     # Here there is no value, so we use 1.
1132 :     $overrides{$name} = 1;
1133 :     }
1134 :     }
1135 :     # Merge the options into the defaults.
1136 :     GetOptions($optionTable, \%overrides);
1137 :     # Translate the remaining parameters.
1138 :     my @retVal = ();
1139 :     for my $inputParm (@inputList) {
1140 :     push @retVal, UnEscape($inputParm);
1141 :     }
1142 :     # Return the results.
1143 :     return ($optionTable, @retVal);
1144 : olson 1.1 }
1145 :    
1146 : parrello 1.9 =head3 Escape
1147 :    
1148 :     C<< my $codedString = Tracer::Escape($realString); >>
1149 :    
1150 : parrello 1.25 Escape a string for use in a command length. Tabs will be replaced by C<\t>, new-lines
1151 : parrello 1.28 replaced by C<\n>, carriage returns will be deleted, and backslashes will be doubled. The
1152 :     result is to reverse the effect of L</UnEscape>.
1153 : parrello 1.9
1154 :     =over 4
1155 :    
1156 :     =item realString
1157 :    
1158 :     String to escape.
1159 :    
1160 :     =item RETURN
1161 :    
1162 :     Escaped equivalent of the real string.
1163 :    
1164 :     =back
1165 :    
1166 :     =cut
1167 :    
1168 :     sub Escape {
1169 : parrello 1.12 # Get the parameter.
1170 :     my ($realString) = @_;
1171 :     # Initialize the return variable.
1172 :     my $retVal = "";
1173 :     # Loop through the parameter string, looking for sequences to escape.
1174 :     while (length $realString > 0) {
1175 :     # Look for the first sequence to escape.
1176 : parrello 1.27 if ($realString =~ /^(.*?)([\n\t\r\\])/) {
1177 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
1178 :     # itself is in $2. First, move the clear text to the return variable.
1179 :     $retVal .= $1;
1180 : parrello 1.14 # Strip the processed section off the real string.
1181 :     $realString = substr $realString, (length $2) + (length $1);
1182 : parrello 1.28 # Get the matched character.
1183 : parrello 1.12 my $char = $2;
1184 : parrello 1.28 # If we have a CR, we are done.
1185 :     if ($char ne "\r") {
1186 :     # It's not a CR, so encode the escape sequence.
1187 :     $char =~ tr/\t\n/tn/;
1188 :     $retVal .= "\\" . $char;
1189 :     }
1190 : parrello 1.12 } else {
1191 :     # Here there are no more escape sequences. The rest of the string is
1192 :     # transferred unmodified.
1193 :     $retVal .= $realString;
1194 :     $realString = "";
1195 :     }
1196 :     }
1197 :     # Return the result.
1198 :     return $retVal;
1199 : parrello 1.9 }
1200 :    
1201 : olson 1.1 =head3 UnEscape
1202 :    
1203 :     C<< my $realString = Tracer::UnEscape($codedString); >>
1204 :    
1205 : parrello 1.25 Replace escape sequences with their actual equivalents. C<\t> will be replaced by
1206 : parrello 1.28 a tab, C<\n> by a new-line character, and C<\\> by a backslash. C<\r> codes will
1207 :     be deleted.
1208 : olson 1.1
1209 :     =over 4
1210 :    
1211 :     =item codedString
1212 :    
1213 :     String to un-escape.
1214 :    
1215 :     =item RETURN
1216 :    
1217 :     Returns a copy of the original string with the escape sequences converted to their actual
1218 :     values.
1219 :    
1220 :     =back
1221 :    
1222 :     =cut
1223 :    
1224 :     sub UnEscape {
1225 : parrello 1.12 # Get the parameter.
1226 :     my ($codedString) = @_;
1227 :     # Initialize the return variable.
1228 :     my $retVal = "";
1229 :     # Only proceed if the incoming string is nonempty.
1230 :     if (defined $codedString) {
1231 :     # Loop through the parameter string, looking for escape sequences. We can't do
1232 : parrello 1.25 # translating because it causes problems with the escaped slash. ("\\t" becomes
1233 :     # "\<tab>" no matter what we do.)
1234 : parrello 1.12 while (length $codedString > 0) {
1235 :     # Look for the first escape sequence.
1236 : parrello 1.27 if ($codedString =~ /^(.*?)\\(\\|n|t|r)/) {
1237 : parrello 1.12 # Here we found it. The text preceding the sequence is in $1. The sequence
1238 :     # itself is in $2. First, move the clear text to the return variable.
1239 :     $retVal .= $1;
1240 :     $codedString = substr $codedString, (2 + length $1);
1241 : parrello 1.28 # Get the escape value.
1242 : parrello 1.12 my $char = $2;
1243 : parrello 1.28 # If we have a "\r", we are done.
1244 :     if ($char ne 'r') {
1245 :     # Here it's not an 'r', so we convert it.
1246 :     $char =~ tr/\\tn/\\\t\n/;
1247 :     $retVal .= $char;
1248 :     }
1249 : parrello 1.12 } else {
1250 :     # Here there are no more escape sequences. The rest of the string is
1251 :     # transferred unmodified.
1252 :     $retVal .= $codedString;
1253 :     $codedString = "";
1254 :     }
1255 :     }
1256 :     }
1257 :     # Return the result.
1258 :     return $retVal;
1259 : olson 1.1 }
1260 :    
1261 :     =head3 ParseRecord
1262 :    
1263 :     C<< my @fields = Tracer::ParseRecord($line); >>
1264 :    
1265 :     Parse a tab-delimited data line. The data line is split into field values. Embedded tab
1266 :     and new-line characters in the data line must be represented as C<\t> and C<\n>, respectively.
1267 :     These will automatically be converted.
1268 :    
1269 :     =over 4
1270 :    
1271 :     =item line
1272 :    
1273 :     Line of data containing the tab-delimited fields.
1274 :    
1275 :     =item RETURN
1276 :    
1277 :     Returns a list of the fields found in the data line.
1278 :    
1279 :     =back
1280 :    
1281 :     =cut
1282 :    
1283 :     sub ParseRecord {
1284 : parrello 1.12 # Get the parameter.
1285 :     my ($line) = @_;
1286 :     # Remove the trailing new-line, if any.
1287 :     chomp $line;
1288 :     # Split the line read into pieces using the tab character.
1289 :     my @retVal = split /\t/, $line;
1290 :     # Trim and fix the escapes in each piece.
1291 :     for my $value (@retVal) {
1292 :     # Trim leading whitespace.
1293 :     $value =~ s/^\s+//;
1294 :     # Trim trailing whitespace.
1295 :     $value =~ s/\s+$//;
1296 :     # Delete the carriage returns.
1297 :     $value =~ s/\r//g;
1298 :     # Convert the escapes into their real values.
1299 :     $value =~ s/\\t/"\t"/ge;
1300 :     $value =~ s/\\n/"\n"/ge;
1301 :     }
1302 :     # Return the result.
1303 :     return @retVal;
1304 : olson 1.1 }
1305 :    
1306 :     =head3 Merge
1307 :    
1308 :     C<< my @mergedList = Tracer::Merge(@inputList); >>
1309 :    
1310 :     Sort a list of strings and remove duplicates.
1311 :    
1312 :     =over 4
1313 :    
1314 :     =item inputList
1315 :    
1316 :     List of scalars to sort and merge.
1317 :    
1318 :     =item RETURN
1319 :    
1320 :     Returns a list containing the same elements sorted in ascending order with duplicates
1321 :     removed.
1322 :    
1323 :     =back
1324 :    
1325 :     =cut
1326 :    
1327 :     sub Merge {
1328 : parrello 1.12 # Get the input list in sort order.
1329 :     my @inputList = sort @_;
1330 :     # Only proceed if the list has at least two elements.
1331 :     if (@inputList > 1) {
1332 :     # Now we want to move through the list splicing out duplicates.
1333 :     my $i = 0;
1334 :     while ($i < @inputList) {
1335 :     # Get the current entry.
1336 :     my $thisEntry = $inputList[$i];
1337 :     # Find out how many elements duplicate the current entry.
1338 :     my $j = $i + 1;
1339 :     my $dup1 = $i + 1;
1340 :     while ($j < @inputList && $inputList[$j] eq $thisEntry) { $j++; };
1341 :     # If the number is nonzero, splice out the duplicates found.
1342 :     if ($j > $dup1) {
1343 :     splice @inputList, $dup1, $j - $dup1;
1344 :     }
1345 :     # Now the element at position $dup1 is different from the element before it
1346 :     # at position $i. We push $i forward one position and start again.
1347 :     $i++;
1348 :     }
1349 :     }
1350 :     # Return the merged list.
1351 :     return @inputList;
1352 : olson 1.1 }
1353 :    
1354 : parrello 1.54 =head3 Percent
1355 :    
1356 :     C<< my $percent = Tracer::Percent($number, $base); >>
1357 :    
1358 :     Returns the percent of the base represented by the given number. If the base
1359 :     is zero, returns zero.
1360 :    
1361 :     =over 4
1362 :    
1363 :     =item number
1364 :    
1365 :     Percent numerator.
1366 :    
1367 :     =item base
1368 :    
1369 :     Percent base.
1370 :    
1371 :     =item RETURN
1372 :    
1373 :     Returns the percentage of the base represented by the numerator.
1374 :    
1375 :     =back
1376 :    
1377 :     =cut
1378 :    
1379 :     sub Percent {
1380 :     # Get the parameters.
1381 :     my ($number, $base) = @_;
1382 :     # Declare the return variable.
1383 :     my $retVal = 0;
1384 :     # Compute the percent.
1385 :     if ($base != 0) {
1386 :     $retVal = $number * 100 / $base;
1387 :     }
1388 :     # Return the result.
1389 :     return $retVal;
1390 :     }
1391 :    
1392 : olson 1.1 =head3 GetFile
1393 :    
1394 : parrello 1.6 C<< my @fileContents = Tracer::GetFile($fileName); >>
1395 : olson 1.1
1396 : parrello 1.35 or
1397 :    
1398 :     C<< my $fileContents = Tracer::GetFile($fileName); >>
1399 :    
1400 :     Return the entire contents of a file. In list context, line-ends are removed and
1401 :     each line is a list element. In scalar context, line-ends are replaced by C<\n>.
1402 : olson 1.1
1403 :     =over 4
1404 :    
1405 :     =item fileName
1406 :    
1407 :     Name of the file to read.
1408 :    
1409 :     =item RETURN
1410 :    
1411 : parrello 1.6 In a list context, returns the entire file as a list with the line terminators removed.
1412 : parrello 1.39 In a scalar context, returns the entire file as a string. If an error occurs opening
1413 :     the file, an empty list will be returned.
1414 : olson 1.1
1415 :     =back
1416 :    
1417 :     =cut
1418 :    
1419 :     sub GetFile {
1420 : parrello 1.12 # Get the parameters.
1421 :     my ($fileName) = @_;
1422 :     # Declare the return variable.
1423 :     my @retVal = ();
1424 :     # Open the file for input.
1425 : parrello 1.60 my $handle = Open(undef, "<$fileName");
1426 :     # Read the whole file into the return variable, stripping off any terminator
1427 :     # characters.
1428 :     my $lineCount = 0;
1429 :     while (my $line = <$handle>) {
1430 :     $lineCount++;
1431 :     $line = Strip($line);
1432 :     push @retVal, $line;
1433 :     }
1434 :     # Close it.
1435 :     close $handle;
1436 :     my $actualLines = @retVal;
1437 : parrello 1.12 # Return the file's contents in the desired format.
1438 : parrello 1.9 if (wantarray) {
1439 : parrello 1.12 return @retVal;
1440 : parrello 1.6 } else {
1441 :     return join "\n", @retVal;
1442 :     }
1443 : olson 1.1 }
1444 :    
1445 : parrello 1.60 =head3 PutFile
1446 :    
1447 :     C<< Tracer::PutFile($fileName, \@lines); >>
1448 :    
1449 :     Write out a file from a list of lines of text.
1450 :    
1451 :     =over 4
1452 :    
1453 :     =item fileName
1454 :    
1455 :     Name of the output file.
1456 :    
1457 :     =item lines
1458 :    
1459 :     Reference to a list of text lines. The lines will be written to the file in order, with trailing
1460 : parrello 1.66 new-line characters. Alternatively, may be a string, in which case the string will be written without
1461 :     modification.
1462 : parrello 1.60
1463 :     =back
1464 :    
1465 :     =cut
1466 :    
1467 :     sub PutFile {
1468 :     # Get the parameters.
1469 :     my ($fileName, $lines) = @_;
1470 :     # Open the output file.
1471 :     my $handle = Open(undef, ">$fileName");
1472 : parrello 1.66 if (ref $lines ne 'ARRAY') {
1473 :     # Here we have a scalar, so we write it raw.
1474 :     print $handle $lines;
1475 :     } else {
1476 :     # Write the lines one at a time.
1477 :     for my $line (@{$lines}) {
1478 :     print $handle "$line\n";
1479 :     }
1480 : parrello 1.60 }
1481 :     # Close the output file.
1482 :     close $handle;
1483 :     }
1484 :    
1485 : olson 1.1 =head3 QTrace
1486 :    
1487 :     C<< my $data = QTrace($format); >>
1488 :    
1489 :     Return the queued trace data in the specified format.
1490 :    
1491 :     =over 4
1492 :    
1493 :     =item format
1494 :    
1495 :     C<html> to format the data as an HTML list, C<text> to format it as straight text.
1496 :    
1497 :     =back
1498 :    
1499 :     =cut
1500 :    
1501 :     sub QTrace {
1502 : parrello 1.12 # Get the parameter.
1503 :     my ($format) = @_;
1504 :     # Create the return variable.
1505 :     my $retVal = "";
1506 : parrello 1.14 # Only proceed if there is an actual queue.
1507 :     if (@Queue) {
1508 :     # Process according to the format.
1509 :     if ($format =~ m/^HTML$/i) {
1510 :     # Convert the queue into an HTML list.
1511 :     $retVal = "<ul>\n";
1512 :     for my $line (@Queue) {
1513 :     my $escapedLine = CGI::escapeHTML($line);
1514 :     $retVal .= "<li>$escapedLine</li>\n";
1515 :     }
1516 :     $retVal .= "</ul>\n";
1517 :     } elsif ($format =~ m/^TEXT$/i) {
1518 :     # Convert the queue into a list of text lines.
1519 :     $retVal = join("\n", @Queue) . "\n";
1520 :     }
1521 :     # Clear the queue.
1522 :     @Queue = ();
1523 : parrello 1.12 }
1524 :     # Return the formatted list.
1525 :     return $retVal;
1526 : olson 1.1 }
1527 :    
1528 :     =head3 Confess
1529 :    
1530 :     C<< Confess($message); >>
1531 :    
1532 : parrello 1.22 Trace the call stack and abort the program with the specified message. When used with
1533 : parrello 1.9 the OR operator and the L</Assert> method, B<Confess> can function as a debugging assert.
1534 : parrello 1.6 So, for example
1535 : olson 1.1
1536 : parrello 1.6 C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1537 : olson 1.1
1538 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1539 :    
1540 :     =over 4
1541 :    
1542 :     =item message
1543 :    
1544 :     Message to include in the trace.
1545 :    
1546 :     =back
1547 :    
1548 :     =cut
1549 :    
1550 :     sub Confess {
1551 : parrello 1.12 # Get the parameters.
1552 :     my ($message) = @_;
1553 :     # Trace the call stack.
1554 : parrello 1.22 Cluck($message);
1555 : parrello 1.12 # Abort the program.
1556 :     croak(">>> $message");
1557 : olson 1.1 }
1558 :    
1559 : parrello 1.6 =head3 Assert
1560 :    
1561 :     C<< Assert($condition1, $condition2, ... $conditionN); >>
1562 :    
1563 :     Return TRUE if all the conditions are true. This method can be used in conjunction with
1564 : parrello 1.29 the OR operator and the L</Confess> method as a debugging assert.
1565 : parrello 1.6 So, for example
1566 :    
1567 :     C<< Assert($recNum >= 0) || Confess("Invalid record number $recNum."); >>
1568 :    
1569 :     Will abort the program with a stack trace if the value of C<$recNum> is negative.
1570 :    
1571 :     =cut
1572 :     sub Assert {
1573 :     my $retVal = 1;
1574 :     LOOP: for my $condition (@_) {
1575 :     if (! $condition) {
1576 :     $retVal = 0;
1577 :     last LOOP;
1578 :     }
1579 :     }
1580 :     return $retVal;
1581 :     }
1582 :    
1583 : olson 1.1 =head3 Cluck
1584 :    
1585 :     C<< Cluck($message); >>
1586 :    
1587 :     Trace the call stack. Note that for best results, you should qualify the call with a
1588 :     trace condition. For example,
1589 :    
1590 :     C<< Cluck("Starting record parse.") if T(3); >>
1591 :    
1592 :     will only trace the stack if the trace level for the package is 3 or more.
1593 :    
1594 :     =over 4
1595 :    
1596 :     =item message
1597 :    
1598 :     Message to include in the trace.
1599 :    
1600 :     =back
1601 :    
1602 :     =cut
1603 :    
1604 :     sub Cluck {
1605 : parrello 1.12 # Get the parameters.
1606 :     my ($message) = @_;
1607 : parrello 1.5 # Trace what's happening.
1608 :     Trace("Stack trace for event: $message");
1609 : parrello 1.12 my $confession = longmess($message);
1610 :     # Convert the confession to a series of trace messages. Note we skip any
1611 : parrello 1.5 # messages relating to calls into Tracer.
1612 : parrello 1.12 for my $line (split /\s*\n/, $confession) {
1613 :     Trace($line) if ($line !~ /Tracer\.pm/);
1614 :     }
1615 : olson 1.1 }
1616 :    
1617 : parrello 1.5 =head3 Min
1618 :    
1619 :     C<< my $min = Min($value1, $value2, ... $valueN); >>
1620 :    
1621 :     Return the minimum argument. The arguments are treated as numbers.
1622 :    
1623 :     =over 4
1624 :    
1625 :     =item $value1, $value2, ... $valueN
1626 :    
1627 :     List of numbers to compare.
1628 :    
1629 :     =item RETURN
1630 :    
1631 :     Returns the lowest number in the list.
1632 :    
1633 :     =back
1634 :    
1635 :     =cut
1636 :    
1637 :     sub Min {
1638 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1639 :     my ($retVal, @values) = @_;
1640 :     # Loop through the remaining parameters, looking for the lowest.
1641 :     for my $value (@values) {
1642 :     if ($value < $retVal) {
1643 :     $retVal = $value;
1644 :     }
1645 :     }
1646 :     # Return the minimum found.
1647 :     return $retVal;
1648 : parrello 1.5 }
1649 :    
1650 :     =head3 Max
1651 :    
1652 :     C<< my $max = Max($value1, $value2, ... $valueN); >>
1653 :    
1654 :     Return the maximum argument. The arguments are treated as numbers.
1655 :    
1656 :     =over 4
1657 :    
1658 :     =item $value1, $value2, ... $valueN
1659 :    
1660 :     List of numbers to compare.
1661 :    
1662 :     =item RETURN
1663 :    
1664 :     Returns the highest number in the list.
1665 :    
1666 :     =back
1667 :    
1668 :     =cut
1669 :    
1670 :     sub Max {
1671 : parrello 1.12 # Get the parameters. Note that we prime the return value with the first parameter.
1672 :     my ($retVal, @values) = @_;
1673 :     # Loop through the remaining parameters, looking for the highest.
1674 :     for my $value (@values) {
1675 :     if ($value > $retVal) {
1676 :     $retVal = $value;
1677 :     }
1678 :     }
1679 :     # Return the maximum found.
1680 :     return $retVal;
1681 : parrello 1.5 }
1682 :    
1683 :     =head3 AddToListMap
1684 :    
1685 : parrello 1.53 C<< Tracer::AddToListMap(\%hash, $key, $value1, $value2, ... valueN); >>
1686 : parrello 1.5
1687 :     Add a key-value pair to a hash of lists. If no value exists for the key, a singleton list
1688 :     is created for the key. Otherwise, the new value is pushed onto the list.
1689 :    
1690 :     =over 4
1691 :    
1692 :     =item hash
1693 :    
1694 :     Reference to the target hash.
1695 :    
1696 :     =item key
1697 :    
1698 :     Key for which the value is to be added.
1699 :    
1700 : parrello 1.53 =item value1, value2, ... valueN
1701 : parrello 1.5
1702 : parrello 1.53 List of values to add to the key's value list.
1703 : parrello 1.5
1704 :     =back
1705 :    
1706 :     =cut
1707 :    
1708 :     sub AddToListMap {
1709 :     # Get the parameters.
1710 : parrello 1.53 my ($hash, $key, @values) = @_;
1711 : parrello 1.5 # Process according to whether or not the key already has a value.
1712 :     if (! exists $hash->{$key}) {
1713 : parrello 1.53 $hash->{$key} = [@values];
1714 : parrello 1.5 } else {
1715 : parrello 1.53 push @{$hash->{$key}}, @values;
1716 : parrello 1.5 }
1717 :     }
1718 : olson 1.1
1719 : parrello 1.7 =head3 DebugMode
1720 :    
1721 :     C<< if (Tracer::DebugMode) { ...code... } >>
1722 :    
1723 : parrello 1.22 Return TRUE if debug mode has been turned on, else output an error
1724 :     page and return FALSE.
1725 : parrello 1.7
1726 :     Certain CGI scripts are too dangerous to exist in the production
1727 :     environment. This method provides a simple way to prevent them
1728 : parrello 1.21 from working unless they are explicitly turned on by creating a password
1729 :     cookie via the B<SetPassword> script. If debugging mode
1730 : parrello 1.22 is not turned on, an error web page will be output directing the
1731 :     user to enter in the correct password.
1732 : parrello 1.7
1733 :     =cut
1734 :    
1735 :     sub DebugMode {
1736 : parrello 1.12 # Declare the return variable.
1737 : parrello 1.21 my $retVal = 0;
1738 : parrello 1.12 # Check the debug configuration.
1739 : parrello 1.21 my $password = CGI::cookie("DebugMode");
1740 :     my $encrypted = Digest::MD5::md5_hex($password);
1741 :     if ($encrypted eq "252dec43280e0c0d6a75ffcec486e61d") {
1742 : parrello 1.12 $retVal = 1;
1743 :     } else {
1744 :     # Here debug mode is off, so we generate an error page.
1745 : parrello 1.61 my $pageString = PageBuilder::Build("<<Html/ErrorPage.html", {}, "Html");
1746 : parrello 1.12 print $pageString;
1747 :     }
1748 :     # Return the determination indicator.
1749 : parrello 1.18 return $retVal;
1750 : parrello 1.9 }
1751 :    
1752 :     =head3 Strip
1753 :    
1754 :     C<< my $string = Tracer::Strip($line); >>
1755 :    
1756 :     Strip all line terminators off a string. This is necessary when dealing with files
1757 :     that may have been transferred back and forth several times among different
1758 :     operating environments.
1759 :    
1760 :     =over 4
1761 :    
1762 :     =item line
1763 :    
1764 :     Line of text to be stripped.
1765 :    
1766 :     =item RETURN
1767 :    
1768 :     The same line of text with all the line-ending characters chopped from the end.
1769 :    
1770 :     =back
1771 :    
1772 :     =cut
1773 :    
1774 :     sub Strip {
1775 : parrello 1.12 # Get a copy of the parameter string.
1776 :     my ($string) = @_;
1777 : parrello 1.29 my $retVal = (defined $string ? $string : "");
1778 : parrello 1.9 # Strip the line terminator characters.
1779 :     $retVal =~ s/(\r|\n)+$//g;
1780 : parrello 1.12 # Return the result.
1781 :     return $retVal;
1782 : parrello 1.9 }
1783 :    
1784 :     =head3 Pad
1785 :    
1786 :     C<< my $paddedString = Tracer::Pad($string, $len, $left, $padChar); >>
1787 :    
1788 :     Pad a string to a specified length. The pad character will be a
1789 :     space, and the padding will be on the right side unless specified
1790 :     in the third parameter.
1791 :    
1792 :     =over 4
1793 :    
1794 :     =item string
1795 :    
1796 :     String to be padded.
1797 :    
1798 :     =item len
1799 :    
1800 :     Desired length of the padded string.
1801 :    
1802 :     =item left (optional)
1803 :    
1804 :     TRUE if the string is to be left-padded; otherwise it will be padded on the right.
1805 :    
1806 :     =item padChar (optional)
1807 :    
1808 : parrello 1.22 Character to use for padding. The default is a space.
1809 :    
1810 : parrello 1.9 =item RETURN
1811 :    
1812 : parrello 1.22 Returns a copy of the original string with the pad character added to the
1813 :     specified end so that it achieves the desired length.
1814 : parrello 1.9
1815 :     =back
1816 :    
1817 :     =cut
1818 :    
1819 :     sub Pad {
1820 : parrello 1.12 # Get the parameters.
1821 :     my ($string, $len, $left, $padChar) = @_;
1822 :     # Compute the padding character.
1823 :     if (! defined $padChar) {
1824 :     $padChar = " ";
1825 :     }
1826 :     # Compute the number of spaces needed.
1827 :     my $needed = $len - length $string;
1828 :     # Copy the string into the return variable.
1829 :     my $retVal = $string;
1830 :     # Only proceed if padding is needed.
1831 :     if ($needed > 0) {
1832 :     # Create the pad string.
1833 :     my $pad = $padChar x $needed;
1834 :     # Affix it to the return value.
1835 :     if ($left) {
1836 :     $retVal = $pad . $retVal;
1837 :     } else {
1838 :     $retVal .= $pad;
1839 :     }
1840 :     }
1841 :     # Return the result.
1842 :     return $retVal;
1843 : parrello 1.7 }
1844 :    
1845 : parrello 1.29 =head3 EOF
1846 :    
1847 :     This is a constant that is lexically greater than any useful string.
1848 :    
1849 :     =cut
1850 :    
1851 :     sub EOF {
1852 :     return "\xFF\xFF\xFF\xFF\xFF";
1853 :     }
1854 :    
1855 : parrello 1.15 =head3 TICK
1856 :    
1857 :     C<< my @results = TICK($commandString); >>
1858 :    
1859 :     Perform a back-tick operation on a command. If this is a Windows environment, any leading
1860 :     dot-slash (C<./> will be removed. So, for example, if you were doing
1861 :    
1862 :     `./protein.cgi`
1863 :    
1864 :     from inside a CGI script, it would work fine in Unix, but would issue an error message
1865 :     in Windows complaining that C<'.'> is not a valid command. If instead you code
1866 :    
1867 :     TICK("./protein.cgi")
1868 :    
1869 :     it will work correctly in both environments.
1870 :    
1871 :     =over 4
1872 :    
1873 :     =item commandString
1874 :    
1875 :     The command string to pass to the system.
1876 :    
1877 :     =item RETURN
1878 :    
1879 :     Returns the standard output from the specified command, as a list.
1880 :    
1881 :     =back
1882 :    
1883 :     =cut
1884 :     #: Return Type @;
1885 :     sub TICK {
1886 :     # Get the parameters.
1887 :     my ($commandString) = @_;
1888 :     # Chop off the dot-slash if this is Windows.
1889 :     if ($FIG_Config::win_mode) {
1890 :     $commandString =~ s!^\./!!;
1891 :     }
1892 :     # Activate the command and return the result.
1893 :     return `$commandString`;
1894 :     }
1895 :    
1896 : parrello 1.35 =head3 ScriptSetup
1897 :    
1898 :     C<< my ($query, $varHash) = ScriptSetup(); >>
1899 :    
1900 :     Perform standard tracing and debugging setup for scripts. The value returned is
1901 :     the CGI object followed by a pre-built variable hash.
1902 :    
1903 :     The C<Trace> query parameter is used to determine whether or not tracing is active and
1904 :     which trace modules (other than C<Tracer> and C<FIG>) should be turned on. Specifying
1905 :     the C<CGI> trace module will trace parameter and environment information. Parameters are
1906 :     traced at level 3 and environment variables at level 4. At the end of the script, the
1907 :     client should call L</ScriptFinish> to output the web page.
1908 :    
1909 :     =cut
1910 :    
1911 :     sub ScriptSetup {
1912 :     # Get the CGI query object.
1913 :     my $query = CGI->new();
1914 :     # Check for tracing. Set it up if the user asked for it.
1915 :     if ($query->param('Trace')) {
1916 : parrello 1.65 # Set up tracing.
1917 :     my $ttype = ($query->param('TF') ? ">$FIG_Config::temp/Trace$$.log" : "QUEUE");
1918 :     TSetup($query->param('Trace') . " FIG Tracer", $ttype);
1919 : parrello 1.35 # Trace the parameter and environment data.
1920 : parrello 1.65 TraceParms($query);
1921 : parrello 1.35 } else {
1922 :     # Here tracing is to be turned off. All we allow is errors traced into the
1923 :     # error log.
1924 :     TSetup("0", "WARN");
1925 :     }
1926 :     # Create the variable hash.
1927 :     my $varHash = { DebugData => '' };
1928 :     # Return the query object and variable hash.
1929 :     return ($query, $varHash);
1930 :     }
1931 :    
1932 : parrello 1.65 =head3 TraceParms
1933 :    
1934 :     C<< Tracer::TraceParms($query); >>
1935 :    
1936 :     Trace the CGI parameters at trace level CGI => 3 and the environment variables
1937 :     at level CGI => 4.
1938 :    
1939 :     =over 4
1940 :    
1941 :     =item query
1942 :    
1943 :     CGI query object containing the parameters to trace.
1944 :    
1945 :     =back
1946 :    
1947 :     =cut
1948 :    
1949 :     sub TraceParms {
1950 :     # Get the parameters.
1951 :     my ($query) = @_;
1952 :     if (T(CGI => 3)) {
1953 :     # Here we want to trace the parameter data.
1954 :     my @names = $query->param;
1955 :     for my $parmName (sort @names) {
1956 :     # Note we skip "Trace", which is for our use only.
1957 :     if ($parmName ne 'Trace') {
1958 :     my @values = $query->param($parmName);
1959 :     Trace("CGI: $parmName = " . join(", ", @values));
1960 :     }
1961 :     }
1962 :     }
1963 :     if (T(CGI => 4)) {
1964 :     # Here we want the environment data too.
1965 :     for my $envName (sort keys %ENV) {
1966 :     Trace("ENV: $envName = $ENV{$envName}");
1967 :     }
1968 :     }
1969 :     }
1970 :    
1971 : parrello 1.35 =head3 ScriptFinish
1972 :    
1973 :     C<< ScriptFinish($webData, $varHash); >>
1974 :    
1975 :     Output a web page at the end of a script. Either the string to be output or the
1976 :     name of a template file can be specified. If the second parameter is omitted,
1977 :     it is assumed we have a string to be output; otherwise, it is assumed we have the
1978 :     name of a template file. The template should have the variable C<DebugData>
1979 :     specified in any form that invokes a standard script. If debugging mode is turned
1980 :     on, a form field will be put in that allows the user to enter tracing data.
1981 :     Trace messages will be placed immediately before the terminal C<BODY> tag in
1982 :     the output, formatted as a list.
1983 :    
1984 :     A typical standard script would loook like the following.
1985 :    
1986 :     BEGIN {
1987 :     # Print the HTML header.
1988 :     print "CONTENT-TYPE: text/html\n\n";
1989 :     }
1990 :     use Tracer;
1991 :     use CGI;
1992 :     use FIG;
1993 :     # ... more uses ...
1994 : parrello 1.61
1995 : parrello 1.35 my ($query, $varHash) = ScriptSetup();
1996 :     eval {
1997 :     # ... get data from $query, put it in $varHash ...
1998 :     };
1999 :     if ($@) {
2000 :     Trace("Script Error: $@") if T(0);
2001 :     }
2002 :     ScriptFinish("Html/MyTemplate.html", $varHash);
2003 :    
2004 :     The idea here is that even if the script fails, you'll see trace messages and
2005 :     useful output.
2006 :    
2007 :     =over 4
2008 :    
2009 :     =item webData
2010 :    
2011 :     A string containing either the full web page to be written to the output or the
2012 :     name of a template file from which the page is to be constructed. If the name
2013 :     of a template file is specified, then the second parameter must be present;
2014 :     otherwise, it must be absent.
2015 :    
2016 :     =item varHash (optional)
2017 :    
2018 :     If specified, then a reference to a hash mapping variable names for a template
2019 :     to their values. The template file will be read into memory, and variable markers
2020 :     will be replaced by data in this hash reference.
2021 :    
2022 : parrello 1.37 =back
2023 :    
2024 : parrello 1.35 =cut
2025 :    
2026 :     sub ScriptFinish {
2027 :     # Get the parameters.
2028 :     my ($webData, $varHash) = @_;
2029 :     # Check for a template file situation.
2030 :     my $outputString;
2031 :     if (defined $varHash) {
2032 : parrello 1.64 # Here we have a template file. We need to determine the template type.
2033 :     my $template;
2034 :     if ($FIG_Config::template_url && $webData =~ /\.php$/) {
2035 :     $template = "$FIG_Config::template_url/$webData";
2036 :     } else {
2037 :     $template = "<<$webData";
2038 :     }
2039 :     $outputString = PageBuilder::Build($template, $varHash, "Html");
2040 : parrello 1.35 } else {
2041 :     # Here the user gave us a raw string.
2042 :     $outputString = $webData;
2043 :     }
2044 :     # Check for trace messages.
2045 :     if ($Destination eq "QUEUE") {
2046 :     # We have trace messages, so we want to put them at the end of the body. This
2047 :     # is either at the end of the whole string or at the beginning of the BODY
2048 :     # end-tag.
2049 :     my $pos = length $outputString;
2050 :     if ($outputString =~ m#</body>#gi) {
2051 :     $pos = (pos $outputString) - 7;
2052 :     }
2053 :     substr $outputString, $pos, 0, QTrace('Html');
2054 :     }
2055 :     # Write the output string.
2056 :     print $outputString;
2057 :     }
2058 :    
2059 : parrello 1.37 =head3 Insure
2060 :    
2061 :     C<< Insure($dirName); >>
2062 :    
2063 :     Insure a directory is present.
2064 :    
2065 :     =over 4
2066 :    
2067 :     =item dirName
2068 :    
2069 :     Name of the directory to check. If it does not exist, it will be created.
2070 :    
2071 :     =back
2072 :    
2073 :     =cut
2074 :    
2075 :     sub Insure {
2076 :     my ($dirName) = @_;
2077 :     if (! -d $dirName) {
2078 :     Trace("Creating $dirName directory.") if T(2);
2079 : parrello 1.43 eval { mkpath $dirName; };
2080 :     if ($@) {
2081 :     Confess("Error creating $dirName: $@");
2082 :     }
2083 :     }
2084 :     }
2085 :    
2086 :     =head3 ChDir
2087 :    
2088 :     C<< ChDir($dirName); >>
2089 :    
2090 :     Change to the specified directory.
2091 :    
2092 :     =over 4
2093 :    
2094 :     =item dirName
2095 :    
2096 :     Name of the directory to which we want to change.
2097 :    
2098 :     =back
2099 :    
2100 :     =cut
2101 :    
2102 :     sub ChDir {
2103 :     my ($dirName) = @_;
2104 :     if (! -d $dirName) {
2105 :     Confess("Cannot change to directory $dirName: no such directory.");
2106 :     } else {
2107 :     Trace("Changing to directory $dirName.") if T(4);
2108 :     my $okFlag = chdir $dirName;
2109 :     if (! $okFlag) {
2110 :     Confess("Error switching to directory $dirName.");
2111 :     }
2112 : parrello 1.37 }
2113 :     }
2114 :    
2115 : parrello 1.59 =head3 SendSMS
2116 :    
2117 :     C<< my $msgID = Tracer::SendSMS($phoneNumber, $msg); >>
2118 :    
2119 :     Send a text message to a phone number using Clickatell. The FIG_Config file must contain the
2120 :     user name, password, and API ID for the relevant account in the hash reference variable
2121 :     I<$FIG_Config::phone>, using the keys C<user>, C<password>, and C<api_id>. For
2122 :     example, if the user name is C<BruceTheHumanPet>, the password is C<silly>, and the API ID
2123 :     is C<2561022>, then the FIG_Config file must contain
2124 :    
2125 :     $phone = { user => 'BruceTheHumanPet',
2126 :     password => 'silly',
2127 :     api_id => '2561022' };
2128 :    
2129 :     The original purpose of this method was to insure Bruce would be notified immediately when the
2130 :     Sprout Load terminates. Care should be taken if you do not wish Bruce to be notified immediately
2131 :     when you call this method.
2132 :    
2133 :     The message ID will be returned if successful, and C<undef> if an error occurs.
2134 :    
2135 :     =over 4
2136 :    
2137 :     =item phoneNumber
2138 :    
2139 :     Phone number to receive the message, in international format. A United States phone number
2140 :     would be prefixed by "1". A British phone number would be prefixed by "44".
2141 :    
2142 :     =item msg
2143 :    
2144 :     Message to send to the specified phone.
2145 :    
2146 :     =item RETURN
2147 :    
2148 :     Returns the message ID if successful, and C<undef> if the message could not be sent.
2149 :    
2150 :     =back
2151 :    
2152 :     =cut
2153 :    
2154 :     sub SendSMS {
2155 :     # Get the parameters.
2156 :     my ($phoneNumber, $msg) = @_;
2157 :     # Declare the return variable. If we do not change it, C<undef> will be returned.
2158 :     my $retVal;
2159 :     # Only proceed if we have phone support.
2160 :     if (! defined $FIG_Config::phone) {
2161 :     Trace("Phone support not present in FIG_Config.") if T(1);
2162 :     } else {
2163 :     # Get the phone data.
2164 :     my $parms = $FIG_Config::phone;
2165 :     # Get the Clickatell URL.
2166 :     my $url = "http://api.clickatell.com/http/";
2167 :     # Create the user agent.
2168 :     my $ua = LWP::UserAgent->new;
2169 :     # Request a Clickatell session.
2170 :     my $resp = $ua->post("$url/sendmsg", { user => $parms->{user},
2171 :     password => $parms->{password},
2172 :     api_id => $parms->{api_id},
2173 :     to => $phoneNumber,
2174 :     text => $msg});
2175 :     # Check for an error.
2176 :     if (! $resp->is_success) {
2177 :     Trace("Alert failed.") if T(1);
2178 :     } else {
2179 :     # Get the message ID.
2180 :     my $rstring = $resp->content;
2181 :     if ($rstring =~ /^ID:\s+(.*)$/) {
2182 :     $retVal = $1;
2183 :     } else {
2184 :     Trace("Phone attempt failed with $rstring") if T(1);
2185 :     }
2186 :     }
2187 :     }
2188 :     # Return the result.
2189 :     return $retVal;
2190 :     }
2191 :    
2192 : parrello 1.55 =head3 CommaFormat
2193 :    
2194 :     C<< my $formatted = Tracer::CommaFormat($number); >>
2195 :    
2196 :     Insert commas into a number.
2197 :    
2198 :     =over 4
2199 :    
2200 :     =item number
2201 :    
2202 :     A sequence of digits.
2203 :    
2204 :     =item RETURN
2205 :    
2206 :     Returns the same digits with commas strategically inserted.
2207 :    
2208 :     =back
2209 :    
2210 :     =cut
2211 :    
2212 :     sub CommaFormat {
2213 :     # Get the parameters.
2214 :     my ($number) = @_;
2215 :     # Pad the length up to a multiple of three.
2216 :     my $padded = "$number";
2217 :     $padded = " " . $padded while length($padded) % 3 != 0;
2218 :     # This is a fancy PERL trick. The parentheses in the SPLIT pattern
2219 :     # cause the delimiters to be included in the output stream. The
2220 :     # GREP removes the empty strings in between the delimiters.
2221 :     my $retVal = join(",", grep { $_ ne '' } split(/(...)/, $padded));
2222 :     # Clean out the spaces.
2223 :     $retVal =~ s/ //g;
2224 :     # Return the result.
2225 :     return $retVal;
2226 :     }
2227 : parrello 1.46 =head3 SetPermissions
2228 :    
2229 : parrello 1.49 C<< Tracer::SetPermissions($dirName, $group, $mask, %otherMasks); >>
2230 : parrello 1.46
2231 :     Set the permissions for a directory and all the files and folders inside it.
2232 :     In addition, the group ownership will be changed to the specified value.
2233 :    
2234 :     This method is more vulnerable than most to permission and compatability
2235 :     problems, so it does internal error recovery.
2236 :    
2237 :     =over 4
2238 :    
2239 :     =item dirName
2240 :    
2241 :     Name of the directory to process.
2242 :    
2243 :     =item group
2244 :    
2245 :     Name of the group to be assigned.
2246 :    
2247 :     =item mask
2248 :    
2249 :     Permission mask. Bits that are C<1> in this mask will be ORed into the
2250 :     permission bits of any file or directory that does not already have them
2251 :     set to 1.
2252 :    
2253 : parrello 1.49 =item otherMasks
2254 :    
2255 :     Map of search patterns to permission masks. If a directory name matches
2256 :     one of the patterns, that directory and all its members and subdirectories
2257 :     will be assigned the new pattern. For example, the following would
2258 :     assign 01664 to most files, but would use 01777 for directories named C<tmp>.
2259 :    
2260 :     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp$' => 01777);
2261 :    
2262 :     The list is ordered, so the following would use 0777 for C<tmp1> and
2263 :     0666 for C<tmp>, C<tmp2>, or C<tmp3>.
2264 :    
2265 :     Tracer::SetPermissions($dirName, 'fig', 01664, '^tmp1' => 0777,
2266 :     '^tmp' => 0666);
2267 :    
2268 :     Note that the pattern matches are all case-insensitive, and only directory
2269 :     names are matched, not file names.
2270 :    
2271 : parrello 1.46 =back
2272 :    
2273 :     =cut
2274 :    
2275 :     sub SetPermissions {
2276 :     # Get the parameters.
2277 : parrello 1.49 my ($dirName, $group, $mask, @otherMasks) = @_;
2278 : parrello 1.46 # Set up for error recovery.
2279 :     eval {
2280 : parrello 1.49 # Switch to the specified directory.
2281 : parrello 1.46 ChDir($dirName);
2282 :     # Get the group ID.
2283 :     my $gid = getgrnam($group);
2284 : parrello 1.50 # Get the mask for tracing.
2285 : parrello 1.51 my $traceMask = sprintf("%04o", $mask) . "($mask)";
2286 : parrello 1.50 Trace("Fixing permissions for directory $dirName using group $group($gid) and mask $traceMask.") if T(2);
2287 : parrello 1.46 my $fixCount = 0;
2288 :     my $lookCount = 0;
2289 :     # @dirs will be a stack of directories to be processed.
2290 :     my @dirs = (getcwd());
2291 :     while (scalar(@dirs) > 0) {
2292 :     # Get the current directory.
2293 :     my $dir = pop @dirs;
2294 : parrello 1.49 # Check for a match to one of the specified directory names. To do
2295 :     # that, we need to pull the individual part of the name off of the
2296 :     # whole path.
2297 :     my $simpleName = $dir;
2298 : parrello 1.57 if ($dir =~ m!/([^/]+)$!) {
2299 : parrello 1.49 $simpleName = $1;
2300 :     }
2301 : parrello 1.56 Trace("Simple directory name for $dir is $simpleName.") if T(4);
2302 : parrello 1.49 # Search for a match.
2303 :     my $match = 0;
2304 :     my $i;
2305 :     for ($i = 0; $i < $#otherMasks && ! $match; $i += 2) {
2306 :     my $pattern = $otherMasks[$i];
2307 :     if ($simpleName =~ /$pattern/i) {
2308 :     $match = 1;
2309 : parrello 1.46 }
2310 : parrello 1.49 }
2311 : parrello 1.52 # Check for a match. Note we use $i-1 because the loop added 2
2312 :     # before terminating due to the match.
2313 :     if ($match && $otherMasks[$i-1] != $mask) {
2314 : parrello 1.49 # This directory matches one of the incoming patterns, and it's
2315 :     # a different mask, so we process it recursively with that mask.
2316 : parrello 1.52 SetPermissions($dir, $group, $otherMasks[$i-1], @otherMasks);
2317 : parrello 1.49 } else {
2318 :     # Here we can process normally. Get all of the non-hidden members.
2319 :     my @submems = OpenDir($dir, 1);
2320 :     for my $submem (@submems) {
2321 :     # Get the full name.
2322 :     my $thisMem = "$dir/$submem";
2323 :     Trace("Checking member $thisMem.") if T(4);
2324 :     $lookCount++;
2325 :     if ($lookCount % 1000 == 0) {
2326 : parrello 1.50 Trace("$lookCount members examined. Current is $thisMem. Mask is $traceMask") if T(3);
2327 : parrello 1.49 }
2328 :     # Fix the group.
2329 :     chown -1, $gid, $thisMem;
2330 :     # Insure this member is not a symlink.
2331 :     if (! -l $thisMem) {
2332 :     # Get its info.
2333 :     my $fileInfo = stat $thisMem;
2334 :     # Only proceed if we got the info. Otherwise, it's a hard link
2335 :     # and we want to skip it anyway.
2336 :     if ($fileInfo) {
2337 :     my $fileMode = $fileInfo->mode;
2338 : parrello 1.58 if (($fileMode & $mask) != $mask) {
2339 : parrello 1.49 # Fix this member.
2340 :     $fileMode |= $mask;
2341 :     chmod $fileMode, $thisMem;
2342 :     $fixCount++;
2343 :     }
2344 :     # If it's a subdirectory, stack it.
2345 :     if (-d $thisMem) {
2346 :     push @dirs, $thisMem;
2347 :     }
2348 : parrello 1.46 }
2349 :     }
2350 :     }
2351 :     }
2352 :     }
2353 :     Trace("$lookCount files and directories processed, $fixCount fixed.") if T(2);
2354 :     };
2355 :     # Check for an error.
2356 :     if ($@) {
2357 :     Confess("SetPermissions error: $@");
2358 :     }
2359 :     }
2360 :    
2361 : parrello 1.62 =head3 CompareLists
2362 :    
2363 :     C<< my ($inserted, $deleted) = Tracer::CompareLists(\@newList, \@oldList, $keyIndex); >>
2364 :    
2365 :     Compare two lists of tuples, and return a hash analyzing the differences. The lists
2366 :     are presumed to be sorted alphabetically by the value in the $keyIndex column.
2367 :     The return value contains a list of items that are only in the new list
2368 :     (inserted) and only in the old list (deleted).
2369 :    
2370 :     =over 4
2371 :    
2372 :     =item newList
2373 :    
2374 :     Reference to a list of new tuples.
2375 :    
2376 :     =item oldList
2377 :    
2378 :     Reference to a list of old tuples.
2379 :    
2380 :     =item keyIndex (optional)
2381 :    
2382 :     Index into each tuple of its key field. The default is 0.
2383 :    
2384 :     =item RETURN
2385 :    
2386 :     Returns a 2-tuple consisting of a reference to the list of items that are only in the new
2387 :     list (inserted) followed by a reference to the list of items that are only in the old
2388 :     list (deleted).
2389 :    
2390 :     =back
2391 :    
2392 :     =cut
2393 :    
2394 :     sub CompareLists {
2395 :     # Get the parameters.
2396 :     my ($newList, $oldList, $keyIndex) = @_;
2397 :     if (! defined $keyIndex) {
2398 :     $keyIndex = 0;
2399 :     }
2400 :     # Declare the return variables.
2401 :     my ($inserted, $deleted) = ([], []);
2402 :     # Loop through the two lists simultaneously.
2403 :     my ($newI, $oldI) = (0, 0);
2404 :     my ($newN, $oldN) = (scalar @{$newList}, scalar @{$oldList});
2405 :     while ($newI < $newN || $oldI < $oldN) {
2406 :     # Get the current object in each list. Note that if one
2407 :     # of the lists is past the end, we'll get undef.
2408 :     my $newItem = $newList->[$newI];
2409 :     my $oldItem = $oldList->[$oldI];
2410 : parrello 1.63 if (! defined($newItem) || defined($oldItem) && $newItem->[$keyIndex] gt $oldItem->[$keyIndex]) {
2411 : parrello 1.62 # The old item is not in the new list, so mark it deleted.
2412 :     push @{$deleted}, $oldItem;
2413 :     $oldI++;
2414 :     } elsif (! defined($oldItem) || $oldItem->[$keyIndex] gt $newItem->[$keyIndex]) {
2415 :     # The new item is not in the old list, so mark it inserted.
2416 :     push @{$inserted}, $newItem;
2417 :     $newI++;
2418 :     } else {
2419 :     # The item is in both lists, so push forward.
2420 :     $oldI++;
2421 :     $newI++;
2422 :     }
2423 :     }
2424 :     # Return the result.
2425 :     return ($inserted, $deleted);
2426 :     }
2427 :    
2428 : parrello 1.65 =head3 GetLine
2429 :    
2430 :     C<< my @data = Tracer::GetLine($handle); >>
2431 :    
2432 :     Read a line of data from a tab-delimited file.
2433 :    
2434 :     =over 4
2435 :    
2436 :     =item handle
2437 :    
2438 :     Open file handle from which to read.
2439 :    
2440 :     =item RETURN
2441 :    
2442 :     Returns a list of the fields in the record read. The fields are presumed to be
2443 :     tab-delimited. If we are at the end of the file, then an empty list will be
2444 :     returned. If an empty line is read, a single list item consisting of a null
2445 :     string will be returned.
2446 :    
2447 :     =back
2448 :    
2449 :     =cut
2450 :    
2451 :     sub GetLine {
2452 :     # Get the parameters.
2453 :     my ($handle) = @_;
2454 :     # Declare the return variable.
2455 :     my @retVal = ();
2456 :     # Read from the file.
2457 :     my $line = <$handle>;
2458 :     # Only proceed if we found something.
2459 :     if (defined $line) {
2460 :     # Remove the new-line.
2461 :     chomp $line;
2462 :     # If the line is empty, return a single empty string; otherwise, parse
2463 :     # it into fields.
2464 :     if ($line eq "") {
2465 :     push @retVal, "";
2466 :     } else {
2467 :     push @retVal, split /\t/,$line;
2468 :     }
2469 :     }
2470 :     # Return the result.
2471 :     return @retVal;
2472 :     }
2473 :    
2474 :     =head3 PutLine
2475 :    
2476 :     C<< Tracer::PutLine($handle, \@fields); >>
2477 :    
2478 :     Write a line of data to a tab-delimited file. The specified field values will be
2479 :     output in tab-separated form, with a trailing new-line.
2480 :    
2481 :     =over 4
2482 :    
2483 :     =item handle
2484 :    
2485 :     Output file handle.
2486 :    
2487 :     =item fields
2488 :    
2489 :     List of field values.
2490 :    
2491 :     =back
2492 :    
2493 :     =cut
2494 :    
2495 :     sub PutLine {
2496 :     # Get the parameters.
2497 :     my ($handle, $fields) = @_;
2498 :     # Write the data.
2499 :     print $handle join("\t", @{$fields}) . "\n";
2500 :     }
2501 :    
2502 :     =head3 GenerateURL
2503 :    
2504 :     C<< my $queryUrl = Tracer::GenerateURL($page, %parameters); >>
2505 :    
2506 :     Generate a GET-style URL for the specified page with the specified parameter
2507 :     names and values. The values will be URL-escaped automatically. So, for
2508 :     example
2509 :    
2510 :     Tracer::GenerateURL("form.cgi", type => 1, string => "\"high pass\" or highway")
2511 :    
2512 :     would return
2513 :    
2514 :     form.cgi?type=1&string=%22high%20pass%22%20or%20highway
2515 :    
2516 :     =over 4
2517 :    
2518 :     =item page
2519 :    
2520 :     Page URL.
2521 :    
2522 :     =item parameters
2523 :    
2524 :     Hash mapping parameter names to parameter values.
2525 :    
2526 :     =item RETURN
2527 :    
2528 :     Returns a GET-style URL that goes to the specified page and passes in the
2529 :     specified parameters and values.
2530 :    
2531 :     =back
2532 :    
2533 :     =cut
2534 :    
2535 :     sub GenerateURL {
2536 :     # Get the parameters.
2537 :     my ($page, %parameters) = @_;
2538 :     # Prime the return variable with the page URL.
2539 :     my $retVal = $page;
2540 :     # Loop through the parameters, creating parameter elements in a list.
2541 :     my @parmList = map { "$_=" . uri_escape($parameters{$_}) } keys %parameters;
2542 :     # If the list is nonempty, tack it on.
2543 :     if (@parmList) {
2544 :     $retVal .= "?" . join("&", @parmList);
2545 :     }
2546 :     # Return the result.
2547 :     return $retVal;
2548 :     }
2549 :    
2550 :     1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3