Everyone is always quick with the regex, but in this case, I think you are painting yourself into a corner when you go with that approach. Just because you can, doesn't mean you should and all that.

So, here's a solution which is really straight-up, and it converts both ways.

Sample input:
3h4m 11040 3h4m 1h2m3s 3723 1h2m3s 1h5s 3605 1h5s 3m4s 184 3m4s 1d2h3m4s 93784 1d2h3m4s 3x -1 2m2m -1 23h59m59s 86399 23h59m59s
The conversion routines:
my @time_values = qw [ d h m s ]; my %time_value = ( d => 86400, h => 3600, m => 60, s => 1 ); sub string_to_time { my ($time) = @_; my $value = 0; foreach my $letter (@time_values) { if ($time =~ s/(\d+)$letter//) { $value += $1 * $time_value{$letter}; } } return -1 if length $time; return $value; } sub time_to_string { my ($time) = @_; my $value = ''; foreach my $letter (@time_values) { my $time_value = $time_value{$letter}; if ($time > $time_value) { $value .= int($time/$time_value).$letter; $time %= $time_value; } } return $value; }
And a quick test-harness for comparisons with other routines:
#!/usr/bin/perl -w use strict; my @test = qw [ 3h4m 1h2m3s 1h5s 3m4s 1d2h3m4s 3x 2m2m 23h59m59s ]; foreach (@test) { my $s2t = string_to_time($_); my $t2s = time_to_string($s2t); printf ("%-15s %-10s %-10s\n", $_, $s2t, $t2s); }
A couple of notes:

In reply to Re: Time to seconds by tadman
in thread Time to seconds by argus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.