in reply to Re: Time to seconds
in thread Time to seconds


Perl has the best regex I know of and two lines IME is more maintainable than two subroutines.
For trivial munging it seems sensible to use regexes, otherwise you code could end up looking like <shudder> Java.. :-S.

The results and error conditions you providecould easily be added to a regex, without compromising robustness or readability

Abigail has a raft of regexes that are both eye watering and mind expanding ;^)

--
Brother Frankus.

¤

Replies are listed 'Best First'.
Re^3: Time to seconds
by tadman (Prior) on Nov 16, 2001 at 00:43 UTC
    Perl does have a very fine regex, as demonstrated below by BrentDax, which is what I was thinking of doing initially, forgetting, at the time, that feature of split().

    No matter how you slice it, though, regex or otherwise, you should put the code into a sub-routine. At least, anyone who is concerned about maintainability would make sure to do that. Having a compact regex is not a license to cut and paste it all over your code, wherever it is required.

    If you're afraid of this code looking like Java, well, that isn't too hard to fix:
    my %time_value = ( d => 86400, h => 3600, m => 60, s => 1 ); sub string_to_time { my ($time) = @_; my $value = 0; map { $value += $1*$time_value{$_} if ($time =~ s/(\d+)$_//) } + sort keys %time_value; return ($value && !length $time)? $value : undef; } sub time_to_string { my ($time) = @_; my $value = ''; (defined $time && $time > 0) || return undef; map { $value .= int($time/$time_value{$_}).$_ and $time %= $ti +me_value{$_} if ($time > $time_value{$_})} sort keys %time_value; return $value; }
    So much for readability and maintainability though.