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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |