Hello,

I wrote some code to convert a time string to seconds.

use strict; use warnings; my $seconds; # 1) min:sec,frac e.g. "5:29,11" # 2) sec,frac e.g. "29,11" # 3) sec e.g. "29" # 4) ,frac e.g. ",11" # 5) min:sec e.g. "5:29" # 6) someth. else e.g. "abc" my $time = " 5:21,11 "; # remove leading and trailing whitespace characters $time =~ s/^\s+|\s+$//g; if( $time =~ m/[^0-9:,]+/ ) { $seconds = -1; } elsif( $time =~ m/((?<min>\d+):)? ((?<sec>\d+))? (,(?<frac>\d+))?/x ) { $seconds = ($+{'min'} * 60) + $+{'sec'} + ($+{'frac'}/(10**length( +$+{'frac'}))); } print("$seconds\n");

I have one problem. I know that if an optional part of the regular expression is not available then it is set to undef. But I also know that undef means in a numeric case the value zero. This behaviour is exactly what I want. Because of use warnings; I get warnings. Of course I want to use the code in a bigger perl script and so it is not a solution to not use use warnings. What do you think how the code could be rewritten to avoid these warnings?

Then of course it is always interesting to see for me how you monks would solve the same problem.

Thank you very much for your help.

Dirk


In reply to Convert time string to seconds by Dirk80

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.