Bio/Root/Utilities.pm

filter: Statementstmt 49.5% 207 / 418 Branchbran 35.3% 87 / 246 Conditioncond 40.0% 36 / 90 MC/DCmcdc 19.6% 10 / 51 Subroutinesub 60.0% 18 / 30 Podpod 100% 23 / 23 totaltotal 44.4% 381 / 858 CC 163 SCAR 42.2
CC
163
Cov
44%
taste_file
272.0
count_files
132.0
send_mail
132.0
CRAP 67.8
« Bio/AlignIO/nexus.pm ↑ Summary Bio/SeqFeature/Tools/IDHandler.pm »
1 package Bio::Root::Utilities;
2 2 $Bio::Root::Utilities::VERSION = '1.7.8';
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use Bio::Root::IO;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use Bio::Root::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use base qw(Bio::Root::Root Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 =head1 NAME
9  
10 Bio::Root::Utilities - general-purpose utilities
11  
12 =head1 SYNOPSIS
13  
14 =head2 Object Creation
15  
16 # Using the supplied singleton object:
17 use Bio::Root::Utilities qw(:obj);
18 $Util->some_method();
19  
20 # Create an object manually:
21 use Bio::Root::Utilities;
22 my $util = Bio::Root::Utilities->new();
23 $util->some_method();
24  
25 $date_stamp = $Util->date_format('yyy-mm-dd');
26  
27 $clean = $Util->untaint($dirty);
28  
29 $compressed = $Util->compress('/home/me/myfile.txt')
30  
31 my ($mean, $stdev) = $Util->mean_stdev( @data );
32  
33 $Util->authority("me@example.com");
34 $Util->mail_authority("Something you should know about...");
35  
36 ...and a host of other methods. See below.
37  
38 =head1 DESCRIPTION
39  
40 Provides general-purpose utilities of potential interest to any Perl script.
41  
42 The C<:obj> tag is a convenience that imports a $Util symbol into your
43 namespace representing a Bio::Root::Utilities object. This saves you
44 from creating your own Bio::Root::Utilities object via
45 C<Bio::Root::Utilities-E<gt>new()> or from prefixing all method calls with
46 C<Bio::Root::Utilities>, though feel free to do these things if desired.
47 Since there should normally not be a need for a script to have more
48 than one Bio::Root::Utilities object, this module thus comes with it's
49 own singleton.
50  
51 =head1 INSTALLATION
52  
53 This module is included with the central Bioperl distribution:
54  
55 http://www.bioperl.org/wiki/Getting_BioPerl
56 ftp://bio.perl.org/pub/DIST
57  
58 Follow the installation instructions included in the README file.
59  
60 =head1 DEPENDENCIES
61  
62 Inherits from L<Bio::Root::Root>, and uses L<Bio::Root::IO>
63 and L<Bio::Root::Exception>.
64  
65 Relies on external executables for file compression/uncompression
66 and sending mail. No paths to these are hard coded but are located
67 as needed.
68  
69 =head1 SEE ALSO
70  
71 http://bioperl.org - Bioperl Project Homepage
72  
73 =head1 ACKNOWLEDGEMENTS
74  
75 This module was originally developed under the auspices of the
76 Saccharomyces Genome Database: http://www.yeastgenome.org/
77  
78 =head1 AUTHOR Steve Chervitz
79  
80 =cut
81  
82 2 ▶use vars qw(@EXPORT_OK %EXPORT_TAGS);
Subroutine BEGIN: called CC=1 SCAR=0.0
83 2 @EXPORT_OK = qw($Util);
84 2 %EXPORT_TAGS = ( obj => [qw($Util)],
85 std => [qw($Util)],);
86  
87 2 ▶use vars qw($ID $Util $GNU_PATH $TIMEOUT_SECS
Subroutine BEGIN: called CC=1 SCAR=0.0
88 @COMPRESSION_UTILS @UNCOMPRESSION_UTILS
89 $DEFAULT_NEWLINE $NEWLINE $AUTHORITY
90 @MONTHS @DAYS $BASE_YEAR $DEFAULT_CENTURY
91 2 );
92  
93 2 $ID = 'Bio::Root::Utilities';
94 # Number of seconds to wait before timing out when reading input (taste_file())
95 2 $TIMEOUT_SECS = 30;
96 2 ▶$NEWLINE = $ENV{'NEWLINE'} || undef;
Condition50%1/2
$ENV{'NEWLINE'} || undef
l!l
02
MC/DC0%0/1
$ENV{'NEWLINE'} || undef
$ENV{'NEWLINE'}
Truth table50%1/2
A
A= $ENV{'NEWLINE'}
Aresult
11
00
97 2 $BASE_YEAR = 1900; # perl's localtime() assumes this for it's year data.
98 # TODO: update this every hundred years. Y2K-sensitive code.
99 2 $DEFAULT_CENTURY = $BASE_YEAR + 100;
100 2 @MONTHS = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
101 2 @DAYS = qw(Sun Mon Tue Wed Thu Fri Sat);
102 # Sets the preference for compression utilities to be used by compress().
103 # The first executable in this list to be found in the current PATH will be used,
104 # unless overridden in the call to that function. See docs for details.
105 2 @COMPRESSION_UTILS = qw(gzip bzip2 zip compress);
106 2 @UNCOMPRESSION_UTILS = qw(gunzip gzip bunzip2 unzip uncompress);
107  
108 # Default person to receive feedback from users and possibly automatic error messages.
109 2 $AUTHORITY = '';
110  
111 # Note: $GNU_PATH is now deprecated, shouldn't be needed since now this module
112 # will automatically locate the compression utility in the current PATH.
113 # Retaining $GNU_PATH for backward compatibility.
114 #
115 # $GNU_PATH points to the directory containing the gzip and gunzip
116 # executables. It may be required for executing gzip/gunzip
117 # in some situations (e.g., when $ENV{PATH} doesn't contain this dir.
118 # Customize $GNU_PATH for your site if the compress() or
119 # uncompress() functions are generating exceptions.
120 2 $GNU_PATH = '';
121 #$GNU_PATH = '/tools/gnu/bin/';
122  
123 2 $DEFAULT_NEWLINE = "\012"; # \n (used if get_newline() fails for some reason)
124  
125 ## Static UTIL object.
126 2 $Util = Bio::Root::Root->new();
127  
128  
129 =head2 date_format
130  
131 Title : date_format
132 Usage : $Util->date_format( [FMT], [DATE])
133 Purpose : -- Get a string containing the formatted date or time
134 : taken when this routine is invoked.
135 : -- Provides a way to avoid using `date`.
136 : -- Provides an interface to localtime().
137 : -- Interconverts some date formats.
138 :
139 : (For additional functionality, use Date::Manip or
140 : Date::DateCalc available from CPAN).
141 Example : $Util->date_format();
142 : $date = $Util->date_format('yyyy-mmm-dd', '11/22/92');
143 Returns : String (unless 'list' is provided as argument, see below)
144 :
145 : 'yyyy-mm-dd' = 1996-05-03 # default format.
146 : 'yyyy-dd-mm' = 1996-03-05
147 : 'yyyy-mmm-dd' = 1996-May-03
148 : 'd-m-y' = 3-May-1996
149 : 'd m y' = 3 May 1996
150 : 'dmy' = 3may96
151 : 'mdy' = May 3, 1996
152 : 'ymd' = 96may3
153 : 'md' = may3
154 : 'year' = 1996
155 : 'hms' = 23:01:59 # when not converting a format, 'hms' can be
156 : # tacked on to any of the above options
157 : # to add the time stamp: eg 'dmyhms'
158 : 'full' | 'unix' = UNIX-style date: Tue May 5 22:00:00 1998
159 : 'list' = the contents of localtime(time) in an array.
160 Argument : (all are optional)
161 : FMT = yyyy-mm-dd | yyyy-dd-mm | yyyy-mmm-dd |
162 : mdy | ymd | md | d-m-y | hms | hm
163 : ('hms' may be appended to any of these to
164 : add a time stamp)
165 :
166 : DATE = String containing date to be converted.
167 : Acceptable input formats:
168 : 12/1/97 (for 1 December 1997)
169 : 1997-12-01
170 : 1997-Dec-01
171 Throws :
172 Comments : If you don't care about formatting or using backticks, you can
173 : always use: $date = `date`;
174 :
175 : For more features, use Date::Manip.pm, (which I should
176 : probably switch to...)
177  
178 See Also : L<file_date()|file_date>, L<month2num()|month2num>
179  
180 =cut
181  
182 #---------------'
183 6 ▶sub date_format {
Subroutine date_format: called CC=31 SCAR=41.7
Pod documented
184 #---------------
185 6 my $self = shift;
186 6 my $option = shift;
187 6 my $date = shift; # optional date to be converted.
188  
189 6 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst);
190  
191 6 ▶ $option ||= 'yyyy-mm-dd';
Condition100%2/2
$option ||= "yyyy-mm-dd"
l!l
51
MC/DC100%1/1
$option ||= "yyyy-mm-dd"
$option
Truth table100%2/2
A
A= $option
Aresult
11
00
192  
193 6 my ($month_txt, $day_txt, $month_num, $fullYear);
194 6 my ($converting, @date);
195  
196 # Load a supplied date for conversion:
197 6 ▶ if(defined($date) && ($date =~ /[\D-]+/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $date and $date =~ /[\D-]+/) { } 3 3 6
Condition100%3/3
defined $date and $date =~ /[\D-]+/
!ll&&!rl&&r
213
MC/DC100%2/2
defined $date and $date =~ /[\D-]+/
defined $date $date =~ /[\D-]+/
Truth table100%3/3
A and B
A= defined $dateB= $date =~ /[\D-]+/
ABresult
0X0
100
111
198 3 $converting = 1;
199 3 ▶ if( $date =~ m{/}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($date =~ m[/]) { } 2 1 3
elsif ($date =~ /(\d{4})-(\d{1,2})-(\d{1,2})/) { } 1 0 1
elsif ($date =~ /(\d{4})-(\w{3,})-(\d{1,2})/) { } 0 0 0
200 2 ($mon,$mday,$year) = split(m{/}, $date);
201 } elsif($date =~ /(\d{4})-(\d{1,2})-(\d{1,2})/) {
202 1 ($year,$mon,$mday) = ($1, $2, $3);
203 } elsif($date =~ /(\d{4})-(\w{3,})-(\d{1,2})/) {
204 0 ($year,$mon,$mday) = ($1, $2, $3);
205 0 $mon = $self->month2num($2);
206 } else {
207 0 print STDERR "\n*** Unsupported input date format: $date\n";
208 }
209 3 ▶ if(length($year) == 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $year == 4) { } 1 2 3
210 1 $fullYear = $year;
211 1 $year = substr $year, 2;
212 } else {
213 # Heuristics to guess what century was intended when a 2-digit year is given
214 # If number is over 50, assume it's for prev century; under 50 = default century.
215 # TODO: keep an eye on this Y2K-sensitive code
216 2 ▶ if ($year > 50) {
Branch: 1 branch
BranchTrueFalseTotal
if ($year > 50) { } 1 1 2
217 1 $fullYear = $DEFAULT_CENTURY + $year - 100;
218 } else {
219 1 $fullYear = $DEFAULT_CENTURY + $year;
220 }
221 }
222 3 $mon -= 1;
223 } else {
224 3 ▶ ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = @date =
Branch: 1 branch
BranchTrueFalseTotal
$date ? : 1 2 3
225 localtime(($date ? $date : time()));
226 3 ▶ return @date if $option =~ /list/i;
Branch: 1 branch
BranchTrueFalseTotal
if $option =~ /list/i 0 3 3
227 3 $fullYear = $BASE_YEAR+$year;
228 }
229 6 $month_txt = $MONTHS[$mon];
230 6 ▶ $day_txt = $DAYS[$wday] if defined $wday;
Branch: 1 branch
BranchTrueFalseTotal
if defined $wday 3 3 6
231 6 $month_num = $mon+1;
232  
233 # print "sec: $sec, min: $min, hour: $hour, month: $mon, m-day: $mday, year: $year\nwday: $wday, yday: $yday, dst: $isdst";<STDIN>;
234  
235 6 ▶ if( $option =~ /yyyy-mm-dd/i ) {
Branch: 13 branches
BranchTrueFalseTotal
if ($option =~ /yyyy-mm-dd/i) { } 2 4 6
elsif ($option =~ /yyyy-dd-mm/i) { } 0 4 4
elsif ($option =~ /yyyy-mmm-dd/i) { } 1 3 4
elsif ($option =~ /full|unix/i) { } 0 3 3
elsif ($option =~ /mdy/i) { } 1 2 3
elsif ($option =~ /ymd/i) { } 0 2 2
elsif ($option =~ /dmy/i) { } 0 2 2
elsif ($option =~ /md/i) { } 1 1 2
elsif ($option =~ /d-m-y/i) { } 1 0 1
elsif ($option =~ /d m y/i) { } 0 0 0
elsif ($option =~ /year/i) { } 0 0 0
elsif ($option =~ /dmy/i) { } 0 0 0
elsif ($option and not $option =~ /hms/i) { } 0 0 0
236 2 $date = sprintf "%4d-%02d-%02d",$fullYear,$month_num,$mday;
237 } elsif( $option =~ /yyyy-dd-mm/i ) {
238 0 $date = sprintf "%4d-%02d-%02d",$fullYear,$mday,$month_num;
239 } elsif( $option =~ /yyyy-mmm-dd/i ) {
240 1 $date = sprintf "%4d-%3s-%02d",$fullYear,$month_txt,$mday;
241 } elsif( $option =~ /full|unix/i ) {
242 0 $date = sprintf "%3s %3s %2d %02d:%02d:%02d %d",$day_txt, $month_txt, $mday, $hour, $min, $sec, $fullYear;
243 } elsif( $option =~ /mdy/i ) {
244 1 $date = "$month_txt $mday, $fullYear";
245 } elsif( $option =~ /ymd/i ) {
246 0 $date = $year."\l$month_txt$mday";
247 } elsif( $option =~ /dmy/i ) {
248 0 $date = $mday."\l$month_txt$year";
249 } elsif( $option =~ /md/i ) {
250 1 $date = "\l$month_txt$mday";
251 } elsif( $option =~ /d-m-y/i ) {
252 1 $date = "$mday-$month_txt-$fullYear";
253 } elsif( $option =~ /d m y/i ) {
254 0 $date = "$mday $month_txt $fullYear";
255 } elsif( $option =~ /year/i ) {
256 0 $date = $fullYear;
257 } elsif( $option =~ /dmy/i ) {
258 0 $date = $mday.'-'.$month_txt.'-'.$fullYear;
259 ▶ } elsif($option and $option !~ /hms/i) {
Condition0%0/3
$option and not $option =~ /hms/i
!ll&&!rl&&r
000
MC/DC0%0/2
$option and not $option =~ /hms/i
$option not $option =~ /hms/i
Truth table0%0/3
A and not(B)
A= $optionB= not $option =~ /hms/i
ABresult
0X0
100
111
260 0 print STDERR "\n*** Unrecognized date format request: $option\n";
261 }
262  
263 6 ▶ if( $option =~ /hms/i and not $converting) {
Branch: 1 branch
BranchTrueFalseTotal
if ($option =~ /hms/i and not $converting) 1 5 6
Condition66%2/3
$option =~ /hms/i and not $converting
!ll&&!rl&&r
501
MC/DC50%1/2
$option =~ /hms/i and not $converting
$option =~ /hms/i not $converting
Truth table66%2/3
A and not(B)
A= $option =~ /hms/iB= not $converting
ABresult
0X0
100
111
264 1 ▶ $date .= " $hour:$min:$sec" if $date;
Branch: 1 branch
BranchTrueFalseTotal
if $date 1 0 1
265 1 ▶ $date ||= "$hour:$min:$sec";
Condition50%1/2
$date ||= "${hour}:${min}:$sec"
l!l
10
MC/DC0%0/1
$date ||= "${hour}:${min}:$sec"
$date
Truth table50%1/2
A
A= $date
Aresult
11
00
266 }
267  
268 6 ▶ return $date || join(" ", @date);
Condition33%1/3
$date || join(' ', @date)
l!l&&r!l&&!r
600
MC/DC0%0/2
$date || join(' ', @date)
$date join(' ', @date)
Truth table33%1/3
A || B
A= $dateB= join(' ', @date)
ABresult
1X1
011
000
269 }
270  
271  
272 =head2 month2num
273  
274 Title : month2num
275 Purpose : Converts a string containing a name of a month to integer
276 : representing the number of the month in the year.
277 Example : $Util->month2num("march"); # returns 3
278 Argument : The string argument must contain at least the first
279 : three characters of the month's name. Case insensitive.
280 Throws : Exception if the conversion fails.
281  
282 =cut
283  
284 #--------------'
285 12 ▶sub month2num {
Subroutine month2num: called CC=3 SCAR=11.1
Pod documented
286 #--------------
287 12 my ($self, $str) = @_;
288  
289 # Get string in proper format for conversion.
290 12 $str = substr($str, 0, 3);
291 12 for my $month (0..$#MONTHS) {
292 78 ▶ return $month+1 if $str =~ /$MONTHS[$month]/i;
Branch: 1 branch
BranchTrueFalseTotal
if $str =~ /$Bio::Root::Utilities::MONTHS[$month]/i 12 66 78
293 }
294 0 $self->throw("Invalid month name: $str");
295 }
296  
297 =head2 num2month
298  
299 Title : num2month
300 Purpose : Does the opposite of month2num.
301 : Converts a number into a string containing a name of a month.
302 Example : $Util->num2month(3); # returns 'Mar'
303 Throws : Exception if supplied number is out of range.
304  
305 =cut
306  
307 #-------------
308 12 ▶sub num2month {
Subroutine num2month: called CC=3 SCAR=12.5
Pod documented
309 #-------------
310 12 my ($self, $num) = @_;
311  
312 12 ▶ $self->throw("Month out of range: $num") if $num < 1 or $num > 12;
Branch: 1 branch
BranchTrueFalseTotal
if $num < 1 or $num > 12 0 12 12
Condition33%1/3
$num < 1 or $num > 12
l!l&&r!l&&!r
0012
MC/DC0%0/2
$num < 1 or $num > 12
$num < 1 $num > 12
Truth table33%1/3
A or B
A= $num < 1B= $num > 12
ABresult
1X1
011
000
313 12 return $MONTHS[$num-1];
314 }
315  
316 =head2 compress
317  
318 Title : compress
319 Usage : $Util->compress(full-path-filename);
320 : $Util->compress(<named parameters>);
321 Purpose : Compress a file.
322 Example : $Util->compress("/usr/people/me/data.txt");
323 : $Util->compress(-file=>"/usr/people/me/data.txt",
324 : -tmp=>1,
325 : -outfile=>"/usr/people/share/data.txt.gz",
326 : -exe=>"/usr/local/bin/fancyzip");
327 Returns : String containing full, absolute path to compressed file
328 Argument : Named parameters (case-insensitive):
329 : -FILE => String (name of file to be compressed, full path).
330 : If the supplied filename ends with '.gz' or '.Z',
331 : that extension will be removed before attempting to compress.
332 : Optional:
333 : -TMP => boolean. If true, (or if user is not the owner of the file)
334 : the file is compressed to a temp file. If false, file may be
335 : clobbered with the compressed version (if using a utility like
336 : gzip, which is the default)
337 : -OUTFILE => String (name of the output compressed file, full path).
338 : -EXE => Name of executable for compression utility to use.
339 : Will supersede those in @COMPRESSION_UTILS defined by
340 : this module. If the absolute path to the executable is not provided,
341 : it will be searched in the PATH env variable.
342 Throws : Exception if file cannot be compressed.
343 : If user is not owner of the file, generates a warning and compresses to
344 : a tmp file. To avoid this warning, use the -o file test operator
345 : and call this function with -TMP=>1.
346 Comments : Attempts to compress using utilities defined in the @COMPRESSION_UTILS
347 : defined by this module, in the order defined. The first utility that is
348 : found to be executable will be used. Any utility defined in optional -EXE param
349 : will be tested for executability first.
350 : To minimize security risks, the -EXE parameter value is untained using
351 : the untaint() method of this module (in 'relaxed' mode to permit path separators).
352  
353 See Also : L<uncompress()|uncompress>
354  
355 =cut
356  
357 #------------'
358 2 ▶sub compress {
Subroutine compress: called CC=22 SCAR=41.0
Pod documented
359 #------------
360 2 my ($self, @args) = @_;
361 # This method formerly didn't use named params and expected fileName, tmp
362 # in that order. This should be backward compatibile.
363 2 my ($fileName, $tmp, $outfile, $exe) = $self->_rearrange([qw(FILE TMP OUTFILE EXE)], @args);
364 2 my ($file, $get, $fmt);
365  
366 # in case the supplied name already has a compressed extension
367 0 ▶ if($fileName =~ /(\.gz|\.Z|\.bz2|\.zip)$/) { $fileName =~ s/$1$//; };
Branch: 1 branch
BranchTrueFalseTotal
if ($fileName =~ /(\.gz|\.Z|\.bz2|\.zip)$/) 0 2 2
368 2 $self->debug("compressing file $fileName");
369  
370 2 my @util_to_use = @COMPRESSION_UTILS;
371  
372 2 ▶ if (defined $exe){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exe) 0 2 2
373 0 $exe = $self->untaint($exe, 1);
374 0 unshift @util_to_use, $exe;
375 }
376  
377 2 my @checked = @util_to_use;
378 2 ▶ $exe ||= '';
Condition50%1/2
$exe ||= ""
l!l
02
MC/DC0%0/1
$exe ||= ""
$exe
Truth table50%1/2
A
A= $exe
Aresult
11
00
379 2 ▶ while (not -x $exe and scalar(@util_to_use)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not -x $exe and scalar @util_to_use) 2 2 4
Condition100%2/2
not -x $exe and scalar @util_to_use
!ll
22
MC/DC100%1/1
not -x $exe and scalar @util_to_use
not -x $exe
Truth table100%2/2
not(A)
A= not -x $exe
Aresult
00
11
380 2 $exe = $self->find_exe(shift @util_to_use);
381 }
382  
383 2 ▶ unless (-x $exe) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-x $exe) 0 2 2
384 0 $self->throw("Can't find compression utility. Looked for @checked");
385 }
386  
387 2 my ($compressed, @cmd, $handle);
388  
389 2 ▶ if(defined($outfile) or $tmp or not -o $fileName) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outfile or $tmp or not -O $fileName) { } 1 1 2
Condition66%4/6
defined $outfile or $tmp or not -O $fileName
l!l&&r!l&&!r
101
defined $outfile or $tmp
l!l&&r!l&&!r
101
MC/DC33%1/3
defined $outfile or $tmp or not -O $fileName
defined $outfile $tmp not -O $fileName
Truth table50%2/4
A or B or not(C)
A= defined $outfileB= $tmpC= not -O $fileName
ABCresult
1XX1
01X1
0011
0000
390 1 ▶ if (defined $outfile) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outfile) { } 1 0 1
391 1 $compressed = $outfile;
392 } else {
393 # obtain a temporary file name (not using the handle)
394 # and insert some special text to flag it as a bioperl-based temp file
395 0 my $io = Bio::Root::IO->new();
396 0 ($handle, $compressed) = $io->tempfile();
397 0 $compressed .= '.tmp.bioperl.gz';
398 }
399  
400 # Use double quotes if executable path have empty spaces
401 1 ▶ if ($exe =~ m/ /) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exe =~ / /) 0 1 1
402 0 $exe = "\"$exe\"";
403 }
404  
405 1 ▶ if ($exe =~ /gzip|bzip2|compress/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($exe =~ /gzip|bzip2|compress/) { } 1 0 1
elsif ($exe eq 'zip') { } 0 0 0
406 1 @cmd = ("$exe -f < \"$fileName\" > \"$compressed\"");
407 } elsif ($exe eq 'zip') {
408 0 @cmd = ("$exe -r \"$fileName.zip\" \"$fileName\"");
409 }
410 1 ▶ not $tmp and
Branch: 1 branch
BranchTrueFalseTotal
$tmp or $self->warn("Not owner of file $fileName. Compressing to temp file $compressed.") 1 0 1
411 $self->warn("Not owner of file $fileName. Compressing to temp file $compressed.");
412 1 $tmp = 1;
413 } else {
414 # Need to compute the compressed name based on exe since we're returning it.
415 1 $compressed = $fileName;
416 1 ▶ if ($exe =~ /gzip/) {
Branch: 4 branches
BranchTrueFalseTotal
if ($exe =~ /gzip/) { } 1 0 1
elsif ($exe =~ /bzip2/) { } 0 0 0
elsif ($exe =~ /zip/) { } 0 0 0
elsif ($exe =~ /compress/) { } 0 0 0
417 1 $compressed .= '.gz';
418 } elsif ($exe =~ /bzip2/) {
419 0 $compressed .= '.bz2';
420 } elsif ($exe =~ /zip/) {
421 0 $compressed .= '.zip';
422 } elsif ($exe =~ /compress/) {
423 0 $compressed .= '.Z';
424 }
425 1 ▶ if ($exe =~ /gzip|bzip2|compress/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($exe =~ /gzip|bzip2|compress/) { } 1 0 1
elsif ($exe eq 'zip') { } 0 0 0
426 1 @cmd = ($exe, '-f', $fileName);
427 } elsif ($exe eq 'zip') {
428 0 @cmd = ($exe, '-r', "$compressed", $fileName);
429 }
430 }
431  
432 2 ▶ if(system(@cmd) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (system(@cmd) != 0) 0 2 2
433 0 $self->throw( -class => 'Bio::Root::SystemException',
434 -text => "Failed to compress file $fileName using $exe: $!");
435 }
436  
437 2 return $compressed;
438 }
439  
440 =head2 uncompress
441  
442 Title : uncompress
443 Usage : $Util->uncompress(full-path-filename);
444 : $Util->uncompress(<named parameters>);
445 Purpose : Uncompress a file.
446 Example : $Util->uncompress("/usr/people/me/data.txt");
447 : $Util->uncompress(-file=>"/usr/people/me/data.txt.gz",
448 : -tmp=>1,
449 : -outfile=>"/usr/people/share/data.txt",
450 : -exe=>"/usr/local/bin/fancyzip");
451 Returns : String containing full, absolute path to uncompressed file
452 Argument : Named parameters (case-insensitive):
453 : -FILE => String (name of file to be uncompressed, full path).
454 : If the supplied filename ends with '.gz' or '.Z',
455 : that extension will be removed before attempting to uncompress.
456 : Optional:
457 : -TMP => boolean. If true, (or if user is not the owner of the file)
458 : the file is uncompressed to a temp file. If false, file may be
459 : clobbered with the uncompressed version (if using a utility like
460 : gzip, which is the default)
461 : -OUTFILE => String (name of the output uncompressed file, full path).
462 : -EXE => Name of executable for uncompression utility to use.
463 : Will supersede those in @UNCOMPRESSION_UTILS defined by
464 : this module. If the absolute path to the executable is not provided,
465 : it will be searched in the PATH env variable.
466 Throws : Exception if file cannot be uncompressed.
467 : If user is not owner of the file, generates a warning and uncompresses to
468 : a tmp file. To avoid this warning, use the -o file test operator
469 : and call this function with -TMP=>1.
470 Comments : Attempts to uncompress using utilities defined in the @UNCOMPRESSION_UTILS
471 : defined by this module, in the order defined. The first utility that is
472 : found to be executable will be used. Any utility defined in optional -EXE param
473 : will be tested for executability first.
474 : To minimize security risks, the -EXE parameter value is untained using
475 : the untaint() method of this module (in 'relaxed' mode to permit path separators).
476  
477 See Also : L<compress()|compress>
478  
479 =cut
480  
481 #------------'
482 2 ▶sub uncompress {
Subroutine uncompress: called CC=20 SCAR=38.9
Pod documented
483 #------------
484 2 my ($self, @args) = @_;
485 # This method formerly didn't use named params and expected fileName, tmp
486 # in that order. This should be backward compatibile.
487 2 my ($fileName, $tmp, $outfile, $exe) = $self->_rearrange([qw(FILE TMP OUTFILE EXE)], @args);
488 2 my ($file, $get, $fmt);
489  
490 # in case the supplied name lacks a compressed extension
491 0 ▶ if(not $fileName =~ /(\.gz|\.Z|\.bz2|\.zip)$/) { $fileName .= $1; };
Branch: 1 branch
BranchTrueFalseTotal
unless ($fileName =~ /(\.gz|\.Z|\.bz2|\.zip)$/) 0 2 2
492 2 $self->debug("uncompressing file $fileName");
493  
494 2 my @util_to_use = @UNCOMPRESSION_UTILS;
495  
496 2 ▶ if (defined $exe){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exe) 0 2 2
497 0 $exe = $self->untaint($exe, 1);
498 0 unshift @util_to_use, $exe;
499 }
500  
501 2 ▶ $exe ||= '';
Condition50%1/2
$exe ||= ""
l!l
02
MC/DC0%0/1
$exe ||= ""
$exe
Truth table50%1/2
A
A= $exe
Aresult
11
00
502 2 ▶ while (not -x $exe and scalar(@util_to_use)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not -x $exe and scalar @util_to_use) 2 2 4
Condition100%2/2
not -x $exe and scalar @util_to_use
!ll
22
MC/DC100%1/1
not -x $exe and scalar @util_to_use
not -x $exe
Truth table100%2/2
not(A)
A= not -x $exe
Aresult
00
11
503 2 $exe = $self->find_exe(shift @util_to_use);
504 }
505  
506 2 ▶ unless (-x $exe) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-x $exe) 0 2 2
507 0 $self->throw("Can't find compression utility. Looked for @util_to_use");
508 }
509  
510 2 my ($uncompressed, @cmd, $handle);
511  
512 2 $uncompressed = $fileName;
513 2 $uncompressed =~ s/\.\w+$//;
514  
515 2 ▶ if(defined($outfile) or $tmp or not -o $fileName) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outfile or $tmp or not -O $fileName) { } 1 1 2
Condition66%4/6
defined $outfile or $tmp or not -O $fileName
l!l&&r!l&&!r
101
defined $outfile or $tmp
l!l&&r!l&&!r
101
MC/DC33%1/3
defined $outfile or $tmp or not -O $fileName
defined $outfile $tmp not -O $fileName
Truth table50%2/4
A or B or not(C)
A= defined $outfileB= $tmpC= not -O $fileName
ABCresult
1XX1
01X1
0011
0000
516 1 ▶ if (defined $outfile) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outfile) { } 1 0 1
517 1 $uncompressed = $outfile;
518 } else {
519 # obtain a temporary file name (not using the handle)
520 0 my $io = Bio::Root::IO->new();
521 0 ($handle, $uncompressed) = $io->tempfile();
522 # insert some special text to flag it as a bioperl-based temp file
523 0 $uncompressed .= '.tmp.bioperl';
524 }
525  
526 # Use double quotes if executable path have empty spaces
527 1 ▶ if ($exe =~ m/ /) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exe =~ / /) 0 1 1
528 0 $exe = "\"$exe\"";
529 }
530  
531 1 ▶ if ($exe =~ /gunzip|bunzip2|uncompress/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($exe =~ /gunzip|bunzip2|uncompress/) { } 1 0 1
elsif ($exe =~ /gzip/) { } 0 0 0
elsif ($exe eq 'unzip') { } 0 0 0
532 1 @cmd = ("$exe -f < \"$fileName\" > \"$uncompressed\"");
533 } elsif ($exe =~ /gzip/) {
534 0 @cmd = ("$exe -df < \"$fileName\" > \"$uncompressed\"");
535 } elsif ($exe eq 'unzip') {
536 0 @cmd = ("$exe -p \"$fileName\" > \"$uncompressed\"");
537 }
538 1 ▶ not $tmp and
Branch: 1 branch
BranchTrueFalseTotal
$tmp or $self->warn("Not owner of file $fileName. Uncompressing to temp file $uncompressed.") 1 0 1
539 $self->warn("Not owner of file $fileName. Uncompressing to temp file $uncompressed.");
540 1 $tmp = 1;
541 } else {
542 1 ▶ if ($exe =~ /gunzip|bunzip2|uncompress/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($exe =~ /gunzip|bunzip2|uncompress/) { } 1 0 1
elsif ($exe =~ /gzip/) { } 0 0 0
elsif ($exe eq 'zip') { } 0 0 0
543 1 @cmd = ($exe, '-f', $fileName);
544 } elsif ($exe =~ /gzip/) {
545 0 @cmd = ($exe, '-df', $fileName);
546 } elsif ($exe eq 'zip') {
547 0 @cmd = ($exe, $fileName);
548 }
549 }
550  
551 2 ▶ if(system(@cmd) != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (system(@cmd) != 0) 0 2 2
552 0 $self->throw( -class => 'Bio::Root::SystemException',
553 -text => "Failed to uncompress file $fileName using $exe: $!");
554 }
555  
556 2 return $uncompressed;
557 }
558  
559  
560 =head2 file_date
561  
562 Title : file_date
563 Usage : $Util->file_date( filename [,date_format])
564 Purpose : Obtains the date of a given file.
565 : Provides flexible formatting via date_format().
566 Returns : String = date of the file as: yyyy-mm-dd (e.g., 1997-10-15)
567 Argument : filename = string, full path name for file
568 : date_format = string, desired format for date (see date_format()).
569 : Default = yyyy-mm-dd
570 Thows : Exception if no file is provided or does not exist.
571 Comments : Uses the mtime field as obtained by stat().
572  
573 =cut
574  
575 #--------------
576 1 ▶sub file_date {
Subroutine file_date: called CC=4 SCAR=15.2
Pod documented
577 #--------------
578 1 my ($self, $file, $fmt) = @_;
579  
580 1 ▶ $self->throw("No such file: $file") if not $file or not -e $file;
Branch: 1 branch
BranchTrueFalseTotal
unless $file and -e $file 0 1 1
Condition33%1/3
$file and -e $file
!ll&&!rl&&r
001
MC/DC0%0/2
$file and -e $file
$file -e $file
Truth table33%1/3
A and B
A= $fileB= -e $file
ABresult
0X0
100
111
581  
582 1 ▶ $fmt ||= 'yyyy-mm-dd';
Condition50%1/2
$fmt ||= "yyyy-mm-dd"
l!l
01
MC/DC0%0/1
$fmt ||= "yyyy-mm-dd"
$fmt
Truth table50%1/2
A
A= $fmt
Aresult
11
00
583  
584 1 my @file_data = stat($file);
585 1 return $self->date_format($fmt, $file_data[9]); # mtime field
586 }
587  
588  
589 =head2 untaint
590  
591 Title : untaint
592 Purpose : To remove nasty shell characters from untrusted data
593 : and allow a script to run with the -T switch.
594 : Potentially dangerous shell meta characters: &;`'\"|*?!~<>^()[]{}$\n\r
595 : Accept only the first block of contiguous characters:
596 : Default allowed chars = "-\w.', ()"
597 : If $relax is true = "-\w.', ()\/=%:^<>*"
598 Usage : $Util->untaint($value, $relax)
599 Returns : String containing the untained data.
600 Argument: $value = string
601 : $relax = boolean
602 Comments:
603 This general untaint() function may not be appropriate for every situation.
604 To allow only a more restricted subset of special characters
605 (for example, untainting a regular expression), then using a custom
606 untainting mechanism would permit more control.
607  
608 Note that special trusted vars (like $0) require untainting.
609  
610 =cut
611  
612 #------------`
613 4 ▶sub untaint {
Subroutine untaint: called CC=5 SCAR=16.1
Pod documented
614 #------------
615 4 my($self,$value,$relax) = @_;
616 4 ▶ $relax ||= 0;
Condition100%2/2
$relax ||= 0
l!l
13
MC/DC100%1/1
$relax ||= 0
$relax
Truth table100%2/2
A
A= $relax
Aresult
11
00
617 4 my $untainted;
618  
619 4 $self->debug("\nUNTAINT: $value\n");
620  
621 4 ▶ unless (defined $value and $value ne '') {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and $value ne "") 1 3 4
Condition66%2/3
defined $value and $value ne ""
!ll&&!rl&&r
013
MC/DC50%1/2
defined $value and $value ne ""
defined $value $value ne ""
Truth table66%2/3
A and B
A= defined $valueB= $value ne ""
ABresult
0X0
100
111
622 1 return $value;
623 }
624  
625 3 ▶ if( $relax ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($relax) { } 1 2 3
626 1 $value =~ /([-\w.\', ()\/=%:^<>*]+)/;
627 1 $untainted = $1
628 # } elsif( $relax == 2 ) { # Could have several degrees of relax.
629 # $value =~ /([-\w.\', ()\/=%:^<>*]+)/;
630 # $untainted = $1
631 } else {
632 2 $value =~ /([-\w.\', ()]+)/;
633 2 $untainted = $1
634 }
635  
636 3 $self->debug("UNTAINTED: $untainted\n");
637  
638 3 $untainted;
639 }
640  
641  
642 =head2 mean_stdev
643  
644 Title : mean_stdev
645 Usage : ($mean, $stdev) = $Util->mean_stdev( @data )
646 Purpose : Calculates the mean and standard deviation given a list of numbers.
647 Returns : 2-element list (mean, stdev)
648 Argument : list of numbers (ints or floats)
649 Thows : n/a
650  
651 =cut
652  
653 #---------------
654 3 ▶sub mean_stdev {
Subroutine mean_stdev: called CC=5 SCAR=16.1
Pod documented
655 #---------------
656 3 my ($self, @data) = @_;
657 3 ▶ return (undef, undef) if not @data; # case of empty @data list
Branch: 1 branch
BranchTrueFalseTotal
unless @data 1 2 3
658 2 my $mean = 0;
659 2 my $N = 0;
660 2 foreach my $num (@data) {
661 4 $mean += $num;
662 4 $N++
663 }
664 2 $mean /= $N;
665 2 my $sum_diff_sqd = 0;
666 2 foreach my $num (@data) {
667 4 $sum_diff_sqd += ($mean - $num) * ($mean - $num);
668 }
669 # if only one element in @data list, unbiased stdev is undefined
670 2 ▶ my $stdev = $N <= 1 ? undef : sqrt( $sum_diff_sqd / ($N-1) );
Branch: 1 branch
BranchTrueFalseTotal
$N <= 1 ? : 1 1 2
671 2 return ($mean, $stdev);
672 }
673  
674  
675 =head2 count_files
676  
677 Title : count_files
678 Purpose : Counts the number of files/directories within a given directory.
679 : Also reports the number of text and binary files in the dir
680 : as well as names of these files and directories.
681 Usage : count_files(\%data)
682 : $data{-DIR} is the directory to be analyzed. Default is ./
683 : $data{-PRINT} = 0|1; if 1, prints results to STDOUT, (default=0).
684 Argument : Hash reference (empty)
685 Returns : n/a;
686 : Modifies the hash ref passed in as the sole argument.
687 : $$href{-TOTAL} scalar
688 : $$href{-NUM_TEXT_FILES} scalar
689 : $$href{-NUM_BINARY_FILES} scalar
690 : $$href{-NUM_DIRS} scalar
691 : $$href{-T_FILE_NAMES} array ref
692 : $$href{-B_FILE_NAMES} array ref
693 : $$href{-DIRNAMES} array ref
694  
695 =cut
696  
697 #----------------
698 0 ▶sub count_files {
Subroutine count_files: not called CC=11 SCAR=48.8
Pod documented
699 #----------------
700 0 my $self = shift;
701 0 my $href = shift; # Reference to an empty hash.
702 0 my( $name, @fileLine);
703 0 ▶ my $dir = $$href{-DIR} || './'; # THIS IS UNIX SPECIFIC? FIXME/TODO
Condition0%0/2
$href->{'-DIR'} || './'
l!l
00
MC/DC0%0/1
$href->{'-DIR'} || './'
$href->{'-DIR'}
Truth table0%0/2
A
A= $href->{'-DIR'}
Aresult
11
00
704 0 ▶ my $print = $$href{-PRINT} || 0;
Condition0%0/2
$href->{'-PRINT'} || 0
l!l
00
MC/DC0%0/1
$href->{'-PRINT'} || 0
$href->{'-PRINT'}
Truth table0%0/2
A
A= $href->{'-PRINT'}
Aresult
11
00
705  
706 ### Make sure $dir ends with /
707 0 ▶ $dir !~ m{/$} and do{ $dir .= '/'; $$href{-DIR} = $dir; };
Branch: 1 branch
BranchTrueFalseTotal
$dir =~ m[/$] or do { $dir .= '/'; $href->{"-DIR"} = $dir } 0 0 0
708  
709 0 ▶ open ( my $PIPE, "ls -1 $dir |" ) || $self->throw("Can't open input pipe: $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $PIPE, "ls -1 $dir |" or $self->throw("Can't open input pipe: $!") 0 0 0
710  
711 ### Initialize the hash data.
712 0 $$href{-TOTAL} = 0;
713 0 $$href{-NUM_TEXT_FILES} = $$href{-NUM_BINARY_FILES} = $$href{-NUM_DIRS} = 0;
714 0 $$href{-T_FILE_NAMES} = [];
715 0 $$href{-B_FILE_NAMES} = [];
716 0 $$href{-DIR_NAMES} = [];
717 0 ▶ while( my $line = <$PIPE> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $PIPE)) 0 0 0
718 0 chomp();
719 0 $$href{-TOTAL}++;
720 0 ▶ if( -T $dir.$line ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-T $dir . $line) 0 0 0
721 0 $$href{-NUM_TEXT_FILES}++;
722 0 push @{$$href{-T_FILE_NAMES}}, $line; }
723 0 ▶ if( -B $dir.$line and not -d $dir.$line) {
Branch: 1 branch
BranchTrueFalseTotal
if (-B $dir . $line and not -d $dir . $line) 0 0 0
Condition0%0/3
-B $dir . $line and not -d $dir . $line
!ll&&!rl&&r
000
MC/DC0%0/2
-B $dir . $line and not -d $dir . $line
-B $dir . $line not -d $dir . $line
Truth table0%0/3
A and not(B)
A= -B $dir . $lineB= not -d $dir . $line
ABresult
0X0
100
111
724 0 $$href{-NUM_BINARY_FILES}++;
725 0 push @{$$href{-B_FILE_NAMES}}, $line; }
726 0 ▶ if( -d $dir.$line ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $dir . $line) 0 0 0
727 0 $$href{-NUM_DIRS}++;
728 0 push @{$$href{-DIR_NAMES}}, $line; }
729 }
730 0 close $PIPE;
731  
732 0 ▶ if( $print) {
Branch: 1 branch
BranchTrueFalseTotal
if ($print) 0 0 0
733 0 printf( "\n%4d %s\n", $$href{-TOTAL}, "total files+dirs in $dir");
734 0 printf( "%4d %s\n", $$href{-NUM_TEXT_FILES}, "text files");
735 0 printf( "%4d %s\n", $$href{-NUM_BINARY_FILES}, "binary files");
736 0 printf( "%4d %s\n", $$href{-NUM_DIRS}, "directories");
737 }
738 }
739  
740  
741 =head2 file_info
742  
743 Title : file_info
744 Purpose : Obtains a variety of date for a given file.
745 : Provides an interface to Perl's stat().
746 Status : Under development. Not ready. Don't use!
747  
748 =cut
749  
750 #--------------
751 0 ▶sub file_info {
Subroutine file_info: not called CC=5 SCAR=34.0
Pod documented
752 #--------------
753 0 my ($self, %param) = @_;
754 0 my ($file, $get, $fmt) = $self->_rearrange([qw(FILE GET FMT)], %param);
755 0 ▶ $get ||= 'all';
Condition0%0/2
$get ||= "all"
l!l
00
MC/DC0%0/1
$get ||= "all"
$get
Truth table0%0/2
A
A= $get
Aresult
11
00
756 0 ▶ $fmt ||= 'yyyy-mm-dd';
Condition0%0/2
$fmt ||= "yyyy-mm-dd"
l!l
00
MC/DC0%0/1
$fmt ||= "yyyy-mm-dd"
$fmt
Truth table0%0/2
A
A= $fmt
Aresult
11
00
757  
758 0 my($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size,
759 $atime, $mtime, $ctime, $blksize, $blocks) = stat $file;
760  
761 0 ▶ if($get =~ /date/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($get =~ /date/i) { } 0 0 0
elsif ($get eq 'all') { } 0 0 0
762 ## I can get the elapsed time since the file was modified but
763 ## it's not so straightforward to get the date in a nice format...
764 ## Think about using a standard CPAN module for this, like
765 ## Date::Manip or Date::DateCalc.
766  
767 0 my $date = $mtime;
768 0 my $elsec = time - $mtime;
769 0 printf "\nFile age: %.0f sec %.0f hrs %.0f days", $elsec, $elsec/3600, $elsec/(3600*24);<STDIN>;
770 0 my $days = sprintf "%.0f", $elsec/(3600*24);
771 } elsif($get eq 'all') {
772 0 return stat $file;
773 }
774 }
775  
776 =head2 delete
777  
778 Title : delete
779 Purpose :
780  
781 =cut
782  
783 #------------
784 0 ▶sub delete {
Subroutine delete: not called CC=4 SCAR=30.0
Pod documented
785 #------------
786 0 my $self = shift;
787 0 my $fileName = shift;
788 0 ▶ if(not -e $fileName) {
Branch: 2 branches
BranchTrueFalseTotal
if (not -e $fileName) { } 0 0 0
elsif (not -O $fileName) { } 0 0 0
789 0 $self->throw("Could not delete file '$fileName': Does not exist.");
790 } elsif(not -o $fileName) {
791 0 $self->throw("Could not delete file '$fileName': Not owner.");
792 }
793 0 ▶ my $ulval = unlink($fileName) > 0
Branch: 1 branch
BranchTrueFalseTotal
my $ulval = unlink($fileName) > 0 or $self->throw("Failed to delete file '${fileName}': $!") 0 0 0
794 or $self->throw("Failed to delete file '$fileName': $!");
795 }
796  
797  
798 =head2 create_filehandle
799  
800 Usage : $object->create_filehandle(<named parameters>);
801 Purpose : Create a FileHandle object from a file or STDIN.
802 : Mainly used as a helper method by read() and get_newline().
803 Example : $data = $object->create_filehandle(-FILE =>'usr/people/me/data.txt')
804 Argument : Named parameters (case-insensitive):
805 : (all optional)
806 : -CLIENT => object reference for the object submitting
807 : the request. Default = $Util.
808 : -FILE => string (full path to file) or a reference
809 : to a FileHandle object or typeglob. This is an
810 : optional parameter (if not defined, STDIN is used).
811 Returns : Reference to a FileHandle object.
812 Throws : Exception if cannot open a supplied file or if supplied with a
813 : reference that is not a FileHandle ref.
814 Comments : If given a FileHandle reference, this method simply returns it.
815 : This method assumes the user wants to read ascii data. So, if
816 : the file is binary, it will be treated as a compressed (gzipped)
817 : file and access it using gzip -ce. The problem here is that not
818 : all binary files are necessarily compressed. Therefore,
819 : this method should probably have a -mode parameter to
820 : specify ascii or binary.
821  
822 See Also : L<get_newline()|get_newline>
823  
824 =cut
825  
826 #---------------------
827 1 ▶sub create_filehandle {
Subroutine create_filehandle: called CC=13 SCAR=41.4
Pod documented
828 #---------------------
829 1 my($self, @param) = @_;
830 1 my($client, $file, $handle) =
831 $self->_rearrange([qw( CLIENT FILE HANDLE )], @param);
832  
833 1 ▶ if(not ref $client) { $client = $self; }
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $client) 1 0 1
834 1 ▶ $file ||= $handle;
Condition33%1/3
$file ||= $handle
l!l&&r!l&&!r
001
MC/DC0%0/2
$file ||= $handle
$file $handle
Truth table33%1/3
A ||= B
A= $fileB= $handle
ABresult
1X1
011
000
835 1 ▶ if( $client->can('file')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client->can("file")) 0 1 1
836 0 $file = $client->file($file);
837 }
838  
839 1 my $FH;
840 my ($handle_ref);
841  
842 1 ▶ if($handle_ref = ref($file)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($handle_ref = ref $file) { } 0 1 1
elsif ($file) { } 0 1 1
843 0 ▶ if($handle_ref eq 'FileHandle') {
Branch: 2 branches
BranchTrueFalseTotal
if ($handle_ref eq 'FileHandle') { } 0 0 0
elsif ($handle_ref eq 'GLOB') { } 0 0 0
844 0 $FH = $file;
845 0 $client->{'_input_type'} = "FileHandle";
846 } elsif($handle_ref eq 'GLOB') {
847 0 $FH = $file;
848 0 $client->{'_input_type'} = "Glob";
849 } else {
850 0 $self->throw(-class => 'Bio::Root::IOException',
851 -text => "Could not read file '$file': Not a FileHandle or GLOB ref.");
852 }
853 0 ▶ $self->verbose > 0 and printf STDERR "$ID: reading data from FileHandle\n";
Branch: 1 branch
BranchTrueFalseTotal
$self->verbose > 0 and printf STDERR "$Bio::Root::Utilities::ID: reading data from FileHandle\n" 0 0 0
854  
855 } elsif($file) {
856 0 $client->{'_input_type'} = "FileHandle for $file";
857  
858 # Use gzip -cd to access compressed data.
859 0 ▶ if( -B $file ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-B $file) 0 0 0
860 0 $client->{'_input_type'} .= " (compressed)";
861 0 my $gzip = $self->find_exe('gzip');
862 0 $file = "$gzip -cd $file |"
863 }
864  
865 0 require FileHandle;
866 0 $FH = FileHandle->new();
867 0 ▶ open ($FH, $file) || $self->throw(-class=>'Bio::Root::FileOpenException',
Branch: 1 branch
BranchTrueFalseTotal
open $FH, $file or $self->throw("-class", "Bio::Root::FileOpenException", "-text", "Could not access data file '${file}': $!") 0 0 0
868 -text =>"Could not access data file '$file': $!");
869 0 ▶ $self->verbose > 0 and printf STDERR "$ID: reading data from file '$file'\n";
Branch: 1 branch
BranchTrueFalseTotal
$self->verbose > 0 and printf STDERR "$Bio::Root::Utilities::ID: reading data from file '${file}'\n" 0 0 0
870  
871 } else {
872 # Read from STDIN.
873 1 $FH = \*STDIN;
874 1 ▶ $self->verbose > 0 and printf STDERR "$ID: reading data from STDIN\n";
Branch: 1 branch
BranchTrueFalseTotal
$self->verbose > 0 and printf STDERR "$Bio::Root::Utilities::ID: reading data from STDIN\n" 0 1 1
875 1 $client->{'_input_type'} = "STDIN";
876 }
877  
878 1 return $FH;
879 }
880  
881 =head2 get_newline
882  
883 Usage : $object->get_newline(<named parameters>);
884 Purpose : Determine the character(s) used for newlines in a given file or
885 : input stream. Delegates to Bio::Root::Utilities::get_newline()
886 Example : $data = $object->get_newline(-CLIENT => $anObj,
887 : -FILE =>'usr/people/me/data.txt')
888 Argument : Same arguemnts as for create_filehandle().
889 Returns : Reference to a FileHandle object.
890 Throws : Propagates any exceptions thrown by Bio::Root::Utilities::get_newline().
891  
892 See Also : L<taste_file()|taste_file>, L<create_filehandle()|create_filehandle>
893  
894 =cut
895  
896 #-----------------
897 1 ▶sub get_newline {
Subroutine get_newline: called CC=9 SCAR=26.4
Pod documented
898 #-----------------
899 1 my($self, @param) = @_;
900  
901 1 ▶ return $NEWLINE if defined $NEWLINE;
Branch: 1 branch
BranchTrueFalseTotal
if defined $Bio::Root::Utilities::NEWLINE 0 1 1
902  
903 1 my($client ) =
904 $self->_rearrange([qw( CLIENT )], @param);
905  
906 1 my $FH = $self->create_filehandle(@param);
907  
908 1 ▶ if(not ref $client) { $client = $self; }
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $client) 1 0 1
909  
910 1 ▶ if($client->{'_input_type'} =~ /STDIN|Glob|compressed/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client->{'_input_type'} =~ /STDIN|Glob|compressed/) { } 1 0 1
911 # Can't taste from STDIN since we can't seek 0 on it.
912 # Are other non special Glob refs seek-able?
913 # Attempt to guess newline based on platform.
914 # Not robust since we could be reading Unix files on a Mac, e.g.
915 1 ▶ if(defined $ENV{'MACPERL'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{'MACPERL'}) { } 0 1 1
916 0 $NEWLINE = "\015"; # \r
917 } else {
918 1 $NEWLINE = "\012"; # \n
919 }
920 } else {
921 0 $NEWLINE = $self->taste_file($FH);
922 }
923  
924 close ($FH) unless ($client->{'_input_type'} eq 'STDIN' ||
925 $client->{'_input_type'} eq 'FileHandle' ||
926 1 ▶ $client->{'_input_type'} eq 'Glob' );
Branch: 1 branch
BranchTrueFalseTotal
unless $client->{"_input_type"} eq "STDIN" or $client->{"_input_type"} eq "FileHandle" or $client->{"_input_type"} eq "Glob" 0 1 1
Condition33%2/6
$client->{"_input_type"} eq "STDIN" or $client->{"_input_type"} eq "FileHandle" or $client->{"_input_type"} eq "Glob"
l!l&&r!l&&!r
100
$client->{"_input_type"} eq "STDIN" or $client->{"_input_type"} eq "FileHandle"
l!l&&r!l&&!r
100
MC/DC0%0/3
$client->{"_input_type"} eq "STDIN" or $client->{"_input_type"} eq "FileHandle" or $client->{"_input_type"} eq "Glob"
$client->{"_input_type"} eq "STDIN" $client->{"_input_type"} eq "FileHandle" $client->{"_input_type"} eq "Glob"
Truth table25%1/4
A or B or C
A= $client->{"_input_type"} eq "STDIN"B= $client->{"_input_type"} eq "FileHandle"C= $client->{"_input_type"} eq "Glob"
ABCresult
1XX1
01X1
0011
0000
927  
928 1 delete $client->{'_input_type'};
929  
930 1 ▶ return $NEWLINE || $DEFAULT_NEWLINE;
Condition33%1/3
$Bio::Root::Utilities::NEWLINE || $Bio::Root::Utilities::DEFAULT_NEWLINE
l!l&&r!l&&!r
100
MC/DC0%0/2
$Bio::Root::Utilities::NEWLINE || $Bio::Root::Utilities::DEFAULT_NEWLINE
$Bio::Root::Utilities::NEWLINE $Bio::Root::Utilities::DEFAULT_NEWLINE
Truth table33%1/3
A || B
A= $Bio::Root::Utilities::NEWLINEB= $Bio::Root::Utilities::DEFAULT_NEWLINE
ABresult
1X1
011
000
931 }
932  
933  
934 =head2 taste_file
935  
936 Usage : $object->taste_file( <FileHandle> );
937 : Mainly a utility method for get_newline().
938 Purpose : Sample a filehandle to determine the character(s) used for a newline.
939 Example : $char = $Util->taste_file($FH)
940 Argument : Reference to a FileHandle object.
941 Returns : String containing an octal represenation of the newline character string.
942 : Unix = "\012" ("\n")
943 : Win32 = "\012\015" ("\r\n")
944 : Mac = "\015" ("\r")
945 Throws : Exception if no input is read within $TIMEOUT_SECS seconds.
946 : Exception if argument is not FileHandle object reference.
947 : Warning if cannot determine neewline char(s).
948 Comments : Based on code submitted by Vicki Brown (vlb@deltagen.com).
949  
950 See Also : L<get_newline()|get_newline>
951  
952 =cut
953  
954 #---------------
955 0 ▶sub taste_file {
Subroutine taste_file: not called CC=16 SCAR=56.1
Pod documented
956 #---------------
957 0 my ($self, $FH) = @_;
958 0 my $BUFSIZ = 256; # Number of bytes read from the file handle.
959 0 my ($buffer, $octal, $str, $irs, $i);
960  
961 0 ▶ ref($FH) eq 'FileHandle' or $self->throw("Can't taste file: not a FileHandle ref");
Branch: 1 branch
BranchTrueFalseTotal
ref $FH eq "FileHandle" or $self->throw("Can't taste file: not a FileHandle ref") 0 0 0
962  
963 0 $buffer = '';
964  
965 # this is a quick hack to check for availability of alarm(); just copied
966 # from Bio/Root/IOManager.pm HL 02/19/01
967 0 my $alarm_available = 1;
968 0 eval {
969 0 alarm(0);
970 };
971 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
972 # alarm() not available (ActiveState perl for win32 doesn't have it.
973 # See jitterbug PR#98)
974 0 $alarm_available = 0;
975 }
976 0 ▶ $SIG{ALRM} = sub { die "Timed out!"; };
Subroutine __ANON__: not called CC=1 SCAR=6.9
977 0 my $result;
978 0 eval {
979 0 ▶ $alarm_available && alarm( $TIMEOUT_SECS );
Branch: 1 branch
BranchTrueFalseTotal
$alarm_available and alarm $Bio::Root::Utilities::TIMEOUT_SECS 0 0 0
980 0 $result = read($FH, $buffer, $BUFSIZ); # read the $BUFSIZ characters of file
981 0 ▶ $alarm_available && alarm(0);
Branch: 1 branch
BranchTrueFalseTotal
$alarm_available and alarm 0 0 0 0
982 };
983 0 ▶ if($@ =~ /Timed out!/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($@ =~ /Timed out!/) { } 0 0 0
elsif (not $result) { } 0 0 0
elsif ($@ =~ /\S/) { } 0 0 0
984 0 $self->throw( "Timed out while waiting for input.",
985 "Timeout period = $TIMEOUT_SECS seconds.\n"
986 ."For longer time before timing out, edit \$TIMEOUT_SECS in Bio::Root::Utilities.pm.");
987  
988 } elsif(not $result) {
989 0 my $err = $@;
990 0 $self->throw("read taste failed to read from FileHandle.", $err);
991  
992 } elsif($@ =~ /\S/) {
993 0 my $err = $@;
994 0 $self->throw("Unexpected error during read: $err");
995 }
996  
997 0 ▶ seek($FH, 0, 0) or $self->throw("seek failed to seek 0 on FileHandle.");
Branch: 1 branch
BranchTrueFalseTotal
seek $FH, 0, 0 or $self->throw("seek failed to seek 0 on FileHandle.") 0 0 0
998  
999 0 my @chars = split(//, $buffer);
1000 0 my $flavor;
1001  
1002 0 ▶ for ($i = 0; $i <$BUFSIZ; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $BUFSIZ) 0 0 0
1003 0 ▶ if (($chars[$i] eq "\012")) {
Branch: 3 branches
BranchTrueFalseTotal
if ($chars[$i] eq "\n") { } 0 0 0
elsif ($chars[$i] eq "\r" and $chars[$i + 1] eq "\n") { } 0 0 0
elsif ($chars[$i] eq "\r") { } 0 0 0
1004 0 ▶ unless ($chars[$i-1] eq "\015") {
Branch: 1 branch
BranchTrueFalseTotal
unless ($chars[$i - 1] eq "\r") 0 0 0
1005 0 $flavor='Unix';
1006 0 $octal = "\012";
1007 0 $str = '\n';
1008 0 $irs = "^J";
1009 0 last;
1010 }
1011 ▶ } elsif (($chars[$i] eq "\015") && ($chars[$i+1] eq "\012")) {
Condition0%0/3
$chars[$i] eq "\r" and $chars[$i + 1] eq "\n"
!ll&&!rl&&r
000
MC/DC0%0/2
$chars[$i] eq "\r" and $chars[$i + 1] eq "\n"
$chars[$i] eq "\r" $chars[$i + 1] eq "\n"
Truth table0%0/3
A and B
A= $chars[$i] eq "\r"B= $chars[$i + 1] eq "\n"
ABresult
0X0
100
111
1012 0 $flavor='DOS';
1013 0 $octal = "\015\012";
1014 0 $str = '\r\n';
1015 0 $irs = "^M^J";
1016 0 last;
1017 } elsif (($chars[$i] eq "\015")) {
1018 0 $flavor='Mac';
1019 0 $octal = "\015";
1020 0 $str = '\r';
1021 0 $irs = "^M";
1022 0 last;
1023 }
1024 }
1025 0 ▶ if (not $octal) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $octal) { } 0 0 0
1026 0 $self->warn("Could not determine newline char. Using '\012'");
1027 0 $octal = "\012";
1028 } else {
1029 #print STDERR "FLAVOR=$flavor, NEWLINE CHAR = $irs\n";
1030 }
1031 0 return($octal);
1032 }
1033  
1034 =head2 file_flavor
1035  
1036 Usage : $object->file_flavor( <filename> );
1037 Purpose : Returns the 'flavor' of a given file (unix, dos, mac)
1038 Example : print "$file has flavor: ", $Util->file_flavor($file);
1039 Argument : filename = string, full path name for file
1040 Returns : String describing flavor of file and handy info about line endings.
1041 : One of these is returned:
1042 : unix (\n or 012 or ^J)
1043 : dos (\r\n or 015,012 or ^M^J)
1044 : mac (\r or 015 or ^M)
1045 : unknown
1046 Throws : Exception if argument is not a file
1047 : Propagates any exceptions thrown by Bio::Root::Utilities::get_newline().
1048  
1049 See Also : L<get_newline()|get_newline>, L<taste_file()|taste_file>
1050  
1051 =cut
1052  
1053 #---------------
1054 1 ▶sub file_flavor {
Subroutine file_flavor: called CC=3 SCAR=11.2
Pod documented
1055 #---------------
1056 1 my ($self, $file) = @_;
1057 1 my %flavors=("\012" =>'unix (\n or 012 or ^J)',
1058 "\015\012" =>'dos (\r\n or 015,012 or ^M^J)',
1059 "\015" =>'mac (\r or 015 or ^M)'
1060 );
1061  
1062 1 ▶ -f $file or $self->throw("Could not determine flavor: arg '$file' is either non existant or is not a file.\n");
Branch: 1 branch
BranchTrueFalseTotal
-f $file or $self->throw("Could not determine flavor: arg '${file}' is either non existant or is not a file.\n") 1 0 1
1063 1 my $octal = $self->get_newline($file);
1064 1 ▶ my $flavor = $flavors{$octal} || "unknown";
Condition50%1/2
$flavors{$octal} || 'unknown'
l!l
10
MC/DC0%0/1
$flavors{$octal} || 'unknown'
$flavors{$octal}
Truth table50%1/2
A
A= $flavors{$octal}
Aresult
11
00
1065 1 return $flavor;
1066 }
1067  
1068 ######################################
1069 ##### Mail Functions ########
1070 ######################################
1071  
1072 =head2 mail_authority
1073  
1074 Title : mail_authority
1075 Usage : $Util->mail_authority( $message )
1076 Purpose : Syntactic sugar to send email to $Bio::Root::Global::AUTHORITY
1077  
1078 See Also : L<send_mail()|send_mail>
1079  
1080 =cut
1081  
1082 #---------------
1083 0 ▶sub mail_authority {
Subroutine mail_authority: not called CC=3 SCAR=24.8
Pod documented
1084 #---------------
1085 0 my( $self, $message ) = @_;
1086 0 my $script = $self->untaint($0,1);
1087  
1088 0 ▶ my $email = $self->{'_auth_email'} || $AUTHORITY;
Condition0%0/3
$self->{'_auth_email'} || $Bio::Root::Utilities::AUTHORITY
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{'_auth_email'} || $Bio::Root::Utilities::AUTHORITY
$self->{'_auth_email'} $Bio::Root::Utilities::AUTHORITY
Truth table0%0/3
A || B
A= $self->{'_auth_email'}B= $Bio::Root::Utilities::AUTHORITY
ABresult
1X1
011
000
1089 0 ▶ if (defined $email) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $email) { } 0 0 0
1090 0 $self->send_mail( -TO=>$AUTHORITY, -SUBJ=>$script, -MSG=>$message);
1091 } else {
1092 0 $self->throw("Can't email authority. No email defined.");
1093 }
1094 }
1095  
1096 =head2 authority
1097  
1098 Title : authority
1099 Usage : $Util->authority('admin@example.com');
1100 Purpose : Set/get the email address that should be notified by mail_authority()
1101  
1102 See Also : L<mail_authority()|mail_authority>
1103  
1104 =cut
1105  
1106 #-------------
1107 0 ▶sub authority {
Subroutine authority: not called CC=2 SCAR=17.9
Pod documented
1108 #-------------
1109 0 my( $self, $email ) = @_;
1110 0 ▶ $self->{'_auth_email'} = $email if defined $email;
Branch: 1 branch
BranchTrueFalseTotal
if defined $email 0 0 0
1111 0 return $self->{'_auth_email'};
1112 }
1113  
1114  
1115 =head2 send_mail
1116  
1117 Title : send_mail
1118 Usage : $Util->send_mail( named_parameters )
1119 Purpose : Provides an interface to mail or sendmail, if available
1120 Returns : n/a
1121 Argument : Named parameters: (case-insensitive)
1122 : -TO => e-mail address to send to
1123 : -SUBJ => subject for message (optional)
1124 : -MSG => message to be sent (optional)
1125 : -CC => cc: e-mail address (optional)
1126 Thows : Exception if TO: address appears bad or is missing.
1127 : Exception if mail cannot be sent.
1128 Comments : Based on TomC's tip at:
1129 : http://www.perl.com/CPAN/doc/FMTEYEWTK/safe_shellings
1130 :
1131 : Using default 'From:' information.
1132 : sendmail options used:
1133 : -t: ignore the address given on the command line and
1134 : get To:address from the e-mail header.
1135 : -oi: prevents send_mail from ending the message if it
1136 : finds a period at the start of a line.
1137  
1138 See Also : L<mail_authority()|mail_authority>
1139  
1140 =cut
1141  
1142  
1143 #-------------
1144 0 ▶sub send_mail {
Subroutine send_mail: not called CC=11 SCAR=48.8
Pod documented
1145 #-------------
1146 0 my( $self, @param) = @_;
1147 0 my($recipient,$subj,$message,$cc) = $self->_rearrange([qw(TO SUBJ MSG CC)],@param);
1148  
1149 0 ▶ $self->throw("Invalid or missing e-mail address: $recipient")
Branch: 1 branch
BranchTrueFalseTotal
unless $recipient =~ /\S+\@\S+/ 0 0 0
1150 if not $recipient =~ /\S+\@\S+/;
1151  
1152 0 ▶ $subj ||= 'empty subject'; $message ||= '';
Condition0%0/4
$subj ||= "empty subject"
l!l
00
$message ||= ""
l!l
00
MC/DC0%0/1
$subj ||= "empty subject"
$subj
MC/DC0%0/1
$message ||= ""
$message
Truth table0%0/2
A
A= $subj
Aresult
11
00
Truth table0%0/2
A
A= $message
Aresult
11
00
1153  
1154 # Best to use mail rather than sendmail. Permissions on sendmail in
1155 # linux distros have been significantly locked down in recent years,
1156 # due to the perception that it is insecure.
1157 0 my ($exe, $ccinfo);
1158 0 ▶ if ($exe = $self->find_exe('mail')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($exe = $self->find_exe('mail')) { } 0 0 0
elsif ($exe = $self->find_exe('sendmail')) { } 0 0 0
1159 0 ▶ if (defined $cc) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cc) 0 0 0
1160 0 $ccinfo = "-c $cc";
1161 }
1162 0 $self->debug("send_mail: $exe -s '$subj' $ccinfo $recipient\n");
1163 0 ▶ open (MAIL, "| $exe -s '$subj' $ccinfo $recipient") ||
Branch: 1 branch
BranchTrueFalseTotal
open MAIL, "| $exe -s '${subj}' $ccinfo $recipient" or $self->throw("Can't send email: mail cannot fork: $!") 0 0 0
1164 $self->throw("Can't send email: mail cannot fork: $!");
1165 0 print MAIL <<QQ_EOFM_QQ;
1166 $message
1167 QQ_EOFM_QQ
1168 0 ▶ $? and $self->warn("mail didn't exit nicely: $?");
Branch: 1 branch
BranchTrueFalseTotal
$? and $self->warn("mail didn't exit nicely: $?") 0 0 0
1169 0 close(MAIL);
1170 } elsif ($exe = $self->find_exe('sendmail')) {
1171 0 ▶ open (SENDMAIL, "| $exe -oi -t") ||
Branch: 1 branch
BranchTrueFalseTotal
open SENDMAIL, "| $exe -oi -t" or $self->throw("Can't send email: sendmail cannot fork: $!") 0 0 0
1172 $self->throw("Can't send email: sendmail cannot fork: $!");
1173 0 print SENDMAIL <<QQ_EOFSM_QQ;
1174 To: $recipient
1175 Subject: $subj
1176 Cc: $cc
1177  
1178 $message
1179  
1180 QQ_EOFSM_QQ
1181 0 ▶ $? and $self->warn("sendmail didn't exit nicely: $?");
Branch: 1 branch
BranchTrueFalseTotal
$? and $self->warn("sendmail didn't exit nicely: $?") 0 0 0
1182  
1183 0 close(SENDMAIL);
1184 } else {
1185 0 $self->throw("Can't find executable for mail or sendmail.");
1186 }
1187 }
1188  
1189  
1190 =head2 find_exe
1191  
1192 Title : find_exe
1193 Usage : $Util->find_exe(name);
1194 Purpose : Locate an executable (for use in a system() call, e.g.))
1195 Example : $Util->find_exe("gzip");
1196 Returns : String containing executable that passes the -x test.
1197 Returns undef if an executable of the supplied name cannot be found.
1198 Argument : Name of executable to be found.
1199 : Can be a full path. If supplied name is not executable, an executable
1200 : of that name will be searched in all directories in the currently
1201 : defined PATH environment variable.
1202 Throws : No exceptions, but issues a warning if multiple paths are found
1203 : for a given name. The first one is used.
1204 Comments : TODO: Confirm functionality on all bioperl-supported platforms.
1205 May get tripped up by variation in path separator character used
1206 for splitting ENV{PATH}.
1207 See Also :
1208  
1209 =cut
1210  
1211 #------------
1212 6 ▶sub find_exe {
Subroutine find_exe: called CC=8 SCAR=21.9
Pod documented
1213 #------------
1214 6 my ($self, $name) = @_;
1215 6 my @bindirs;
1216 6 ▶ if ($^O =~ m/mswin/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($^O =~ /mswin/i) { } 0 6 6
1217 0 @bindirs = split ';', $ENV{'PATH'};
1218 # Add usual executable extension if missing or -x won't work
1219 0 ▶ $name.= '.exe' if ($name !~ m/\.exe$/i);
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /\.exe$/i 0 0 0
1220 }
1221 else {
1222 6 @bindirs = split ':', $ENV{'PATH'};
1223 }
1224 6 my $exe = $name;
1225 6 ▶ unless (-x $exe) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-x $exe) 6 0 6
1226 6 undef $exe;
1227 6 my @exes;
1228 6 foreach my $d (@bindirs) {
1229 # Note: Windows also understand '/' as folder separator,
1230 # so there is no need to use a conditional with '\'
1231 60 ▶ push(@exes, "$d/$name") if -x "$d/$name";
Branch: 1 branch
BranchTrueFalseTotal
if -x "$d/$name" 10 50 60
1232 }
1233 6 ▶ if (scalar @exes) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @exes) 5 1 6
1234 5 $exe = $exes[0];
1235 5 ▶ if (defined $exes[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $exes[1]) 5 0 5
1236 5 $self->warn("find_exe: Multiple paths to '$name' found. Using $exe.");
1237 }
1238 }
1239 }
1240 6 return $exe;
1241 }
1242  
1243  
1244 ######################################
1245 ### Interactive Functions #####
1246 ######################################
1247  
1248  
1249 =head2 yes_reply
1250  
1251 Title : yes_reply()
1252 Usage : $Util->yes_reply( [query_string]);
1253 Purpose : To test an STDIN input value for affirmation.
1254 Example : print +( $Util->yes_reply('Are you ok') ? "great!\n" : "sorry.\n" );
1255 : $Util->yes_reply('Continue') || die;
1256 Returns : Boolean, true (1) if input string begins with 'y' or 'Y'
1257 Argument: query_string = string to be used to prompt user (optional)
1258 : If not provided, 'Yes or no' will be used.
1259 : Question mark is automatically appended.
1260  
1261 =cut
1262  
1263 #-------------
1264 0 ▶sub yes_reply {
Subroutine yes_reply: not called CC=2 SCAR=17.9
Pod documented
1265 #-------------
1266 0 my $self = shift;
1267 0 my $query = shift;
1268 0 my $reply;
1269 0 ▶ $query ||= 'Yes or no';
Condition0%0/2
$query ||= "Yes or no"
l!l
00
MC/DC0%0/1
$query ||= "Yes or no"
$query
Truth table0%0/2
A
A= $query
Aresult
11
00
1270 0 print "\n$query? (y/n) [n] ";
1271 0 chomp( $reply = <STDIN> );
1272 0 $reply =~ /^y/i;
1273 }
1274  
1275  
1276  
1277 =head2 request_data
1278  
1279 Title : request_data()
1280 Usage : $Util->request_data( [value_name]);
1281 Purpose : To request data from a user to be entered via keyboard (STDIN).
1282 Example : $name = $Util->request_data('Name');
1283 : # User will see: % Enter Name:
1284 Returns : String, (data entered from keyboard, sans terminal newline.)
1285 Argument: value_name = string to be used to prompt user.
1286 : If not provided, 'data' will be used, (not very helpful).
1287 : Question mark is automatically appended.
1288  
1289 =cut
1290  
1291 #----------------
1292 0 ▶sub request_data {
Subroutine request_data: not called CC=2 SCAR=17.9
Pod documented
1293 #----------------
1294 0 my $self = shift;
1295 0 ▶ my $data = shift || 'data';
Condition0%0/2
shift() || 'data'
l!l
00
MC/DC0%0/1
shift() || 'data'
shift()
Truth table0%0/2
A
A= shift()
Aresult
11
00
1296 0 print "Enter $data: ";
1297 # Remove the terminal newline char.
1298 0 chomp($data = <STDIN>);
1299 0 $data;
1300 }
1301  
1302 =head2 quit_reply
1303  
1304 Title : quit_reply
1305 Usage :
1306 Purpose :
1307  
1308 =cut
1309  
1310 0 ▶sub quit_reply {
Subroutine quit_reply: not called CC=1 SCAR=6.9
Pod documented
1311 # Not much used since you can use request_data()
1312 # and test for an empty string.
1313 0 my $self = shift;
1314 0 my $reply;
1315 0 chop( $reply = <STDIN> );
1316 0 $reply =~ /^q.*/i;
1317 }
1318  
1319  
1320 =head2 verify_version
1321  
1322 Purpose : Checks the version of Perl used to invoke the script.
1323 : Aborts program if version is less than the given argument.
1324 Usage : verify_version('5.000')
1325  
1326 =cut
1327  
1328 #------------------
1329 0 ▶sub verify_version {
Subroutine verify_version: not called CC=2 SCAR=17.9
Pod documented
1330 #------------------
1331 0 my $self = shift;
1332 0 my $reqVersion = shift;
1333  
1334 0 ▶ $] < $reqVersion and do {
Branch: 1 branch
BranchTrueFalseTotal
$] < $reqVersion and do { printf STDERR "\a\n%s %0.3f.\n", "** Sorry. This Perl script requires at least version", $reqVersion; printf STDERR "%s %0.3f %s\n\n", "You are running Perl version", $], "Please update your Perl!\n\n"; exit 1 } 0 0 0
1335 0 printf STDERR ( "\a\n%s %0.3f.\n", "** Sorry. This Perl script requires at least version", $reqVersion);
1336 0 printf STDERR ( "%s %0.3f %s\n\n", "You are running Perl version", $], "Please update your Perl!\n\n" );
1337 0 exit(1);
1338 }
1339 }
1340  
1341 2 1;
1342  
1343 __END__
« Bio/AlignIO/nexus.pm ↑ Summary Bio/SeqFeature/Tools/IDHandler.pm »