aware74 has asked for the wisdom of the Perl Monks concerning the following question:
I'm still pretty new to Perl, and I want to write a Perl script that will take the elapsed time that is returned by the command
/bin/ps -p $pid -o etime --no-headingand convert it into seconds.
Below is my first attempt at it. But my code currently assumes that there will always be an hour component, and there will not be. Can someone give me some pointers on how to modify the regular expression for time to accept input like "32:05" in addition to "11:32:05"?
Any additional suggestions that you may have to improve the quality, readability and maintainability of the code would be greatly appreciated.
Thanks in advance,
Mike
#!/usr/bin/perl # URL that generated the regex part of this code: # http://txt2re.com/index.php3?s=345-11:24:09&9&1 use strict; use warnings; my $inputErrMsg = "\nThe input must be of the form <DD->hh:mm:ss\n\n"; my $exitCode=0; my $inputTxt=$ARGV[0]; if ( ( defined($inputTxt) ) && ( $inputTxt ne "" ) ) { $inputTxt = &trim($inputTxt); my $optionalDaysInYearRegex='^(\\d{1,3}-)?'; # optional 3-digit i +nteger followed by a dash my $timeRegex ='((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5 +][0-9])(?::[0-5][0-9]))'; # time in hh:mm:ss format (want it to becom +e <hh:>mm:ss format) my $clockTimeRegex = $optionalDaysInYearRegex.$timeRegex; if($inputTxt =~ m/$clockTimeRegex/is) { my $optionalDaysInYearStruct = $1; my $days = 0; my $nullPlaceholder = ""; if(defined($optionalDaysInYearStruct)) { ($days,$nullPlaceholder) = split('-', $optionalDaysInYearS +truct); } my $time=$2; #print STDERR "\ndays == $days; time == $time\n\n"; my ($hours,$mins,$secs) = split('\:', $time); # I know this wi +ll have to change to work correctly once hours are no longer a given my $totalSecs = ( $days * 24 * 3600 ) + ( $hours * 3600 ) + ( +$mins * 60 ) + $secs; print "$totalSecs\n"; } else { print "$inputErrMsg"; $exitCode = 1; } } else { print "$inputErrMsg"; $exitCode = 1; } sub trim($) { my $string = shift; $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; } exit $exitCode;
|
|---|