Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: A regular expression that will work for (hh:)mm:ss [converting clock time to seconds]

by GrandFather (Saint)
on Apr 13, 2012 at 03:23 UTC ( [id://964861]=note: print w/replies, xml ) Need Help??


in reply to A regular expression that will work for (hh:)mm:ss [converting clock time to seconds]

First off, a few style related points to ponder:

  1. Be consistent with white space usage. Perl::Tidy is great for cleaning up code
  2. Don't use & to call subs, it doesn't do what you think. Use subName(...) instead.
  3. Don't use prototypes. They really don't do what you think.
  4. Use early exits to clean up error handling logic and remove levels of indentation.

I'd put the code into a subroutine to make testing easier. I'd also simplify the time matching regex and perform the range checking outside the regex. Something like:

#!/usr/bin/perl use strict; use warnings; for my $test ('', '234-10:23', '0:0:1', '0:1', '24:60') { my $fail = parseTime($test); print "Failed parsing '$test': $fail\n" if $fail; } sub parseTime { my ($inputTxt) = @_; return "Bad input value" if !defined $inputTxt || !length $inputTx +t; $inputTxt =~ s/^\s+|\s+$//g; return "Bad time string" if $inputTxt !~ /^(?:(\d{1,3})-)?(?:(\d+):)?(\d+):(\d+)/; my ($days, $hours, $mins, $secs) = map {$_ || 0} $1, $2, $3, $4; return "Bad day count: $days" if $days > 366 && $days >= 0; return "Bad hour value: $hours" if $hours > 23 && $hours >= 0; return "Bad minutes value: $mins" if $mins > 59 && $mins >= 0; return "Bad seconds value: $secs" if $secs > 59 && $secs >= 0; my $totalSecs = ($days * 24 * 3600) + ($hours * 3600) + ($mins * 60) + $secs; print "$inputTxt - ${totalSecs}s\n"; return; }

Prints:

Failed parsing '': Bad input value 234-10:23 - 20218223s 0:0:1 - 1s 0:1 - 1s Failed parsing '24:60': Bad seconds value: 60
True laziness is hard work

Replies are listed 'Best First'.
Re^2: A regular expression that will work for (hh:)mm:ss [converting clock time to seconds]
by aware74 (Initiate) on Apr 13, 2012 at 16:31 UTC

    Thanks very much for taking the time to provide detailed feedback as well as a much easier-to-test alternative.

    I thought that & was just the way you call subroutines, but I have more to learn. And I like the fact that by making it a subroutine you can much more easily test your code in place.

    Thanks again,
    Mike

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://964861]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-03-29 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found