use strict; use warnings; my @time_str_list = ( "abc", "1abc", ":", ":,", "5:29,11", "29,11", "29:00", "29:00,3", "29:00,303", "9:13,07", ",11", "0:11", "5:29" ); my $seconds; for my $time_str ( @time_str_list ) { &convertTimeStrToSeconds($time_str, \$seconds); next unless defined $seconds; print("$time_str\n"); print("$seconds\n"); &convertSecondsToTimeStr($seconds, \$time_str); next unless defined $time_str; print("$time_str\n"); print("\n"); } sub convertTimeStrToSeconds { my ($time_str, $ref_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" $$ref_seconds = undef; # 6) # remove leading and trailing whitespace characters $time_str =~ s/^\s+|\s+$//g; # valid time string if( ($time_str =~ m/^(?\d+):(?\d+),(?\d+)$/) ||# 1) ($time_str =~ m/^(?\d+),(?\d+)$/) || # 2) ($time_str =~ m/^(?\d+)$/) || # 3) ($time_str =~ m/^,(?\d+)$/) || # 4) ($time_str =~ m/^(?\d+):(?\d+)$/) ) # 5) { no warnings 'uninitialized'; # intention: undef treated as zero $$ref_seconds = ($+{'min'} * 60.0) + $+{'sec'} + ($+{'frac'}/(10**length($+{'frac'}))); } } sub convertSecondsToTimeStr { my ($seconds, $ref_time_str) = @_; $$ref_time_str = undef; if( $seconds > 0 ) { my $min = int($seconds / 60.0); my $sec = $seconds % 60.0; my $frac = int(sprintf("%.2f", ($seconds - int($seconds))*100.0)); $$ref_time_str = "$min:" if( $min > 0 ); $$ref_time_str .= sprintf("%02d", $sec) if ( ($min > 0) || ($sec > 0) ); $$ref_time_str .= ",$frac" if ( $frac > 0 ); } }