package My::TimeCalc; use strict; use overload ('""' => 'asString', '+' => 'add', '-' => 'subtract', '*' => 'mult', '/' => 'divide', '<=>' => 'compare'); sub new { my ($class, $time_str) = @_; my $seconds; my $self = \$seconds; bless($self, $class); $time_str = defined($time_str) ? $time_str : "0"; return( $self->fromString($time_str) ); } sub sec { my ($self) = @_; return $$self; } sub asString { my ($self, $precision) = @_; $precision = defined($precision)?$precision:2; my $min = int(abs($$self) / 60.0); my $sec = abs($$self) % 60.0; my $frac = sprintf("%.${precision}f", abs($$self - int($$self))) * 10**$precision; my $time_str = ""; if( $$self < 0 ) { $time_str = "-"; } $time_str .= "$min:" if( $min != 0 ); $time_str .= sprintf("%02d", $sec) if ( ($min != 0) || ($sec != 0) ); $time_str .= "," . sprintf("%0${precision}d", $frac) if ( $frac != 0 ); if( ($min == 0) && ($sec == 0) && ($frac == 0) ) { $time_str = "0"; } return( $time_str ); } sub fromString { my ($self, $time_str) = @_; # 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" # Note: instead of "," you can also take "."! # remove leading and trailing whitespace characters $time_str =~ s/^\s+|\s+$//g; # valid time string if( ($time_str =~ m/^(?\d+):(?\d+)(,|\.)(?\d+)$/) || ($time_str =~ m/^(?\d+)(,|\.)(?\d+)$/) || ($time_str =~ m/^(?\d+)$/) || ($time_str =~ m/^(,|\.)(?\d+)$/) || ($time_str =~ m/^(?\d+):(?\d+)$/) ) { no warnings 'uninitialized'; # intention: undef treated as zero $$self = ($+{'min'} * 60.0) + $+{'sec'} + ($+{'frac'}/(10**length($+{'frac'}))); return( $self ); } return( undef ); } sub add { my ($self, $another) = @_; my $result; if( ref($another) eq "My::TimeCalc" ) { $result = $self->sec() + $another->sec(); } else { $result = $self->sec() + $another; } return( new My::TimeCalc($result) ); } sub subtract { my ($self, $another) = @_; my $result; if( ref($another) eq "My::TimeCalc" ) { $result = $self->sec() - $another->sec(); } else { $result = $self->sec() - $another; } return( new My::TimeCalc($result) ); } sub mult { my ($self, $another) = @_; my $result; if( ref($another) eq "My::TimeCalc" ) { $result = $self->sec() * $another->sec(); } else { $result = $self->sec() * $another; } return( new My::TimeCalc($result) ); } sub divide { my ($self, $another) = @_; my $result; if( ref($another) eq "My::TimeCalc" ) { $result = $self->sec() / $another->sec(); } else { $result = $self->sec() / $another; } return( new My::TimeCalc($result) ); } sub compare { my ($self, $another) = @_; if( ref($another) eq "My::TimeCalc" ) { return( $self->sec() <=> $another->sec() ); } else { return( $self->sec() <=> $another ); } } 1;