in reply to Re: Convert time into seconds
in thread Convert time into seconds

Thank you all and thanks Random_Walk for providing the simple solution for this. I loved writing my first simple perl script. :)

Here is the script I created taking a string from the log (though hard coded).

#!/usr/bin/perl my %Minutes = (); my %Seconds = (); my %Seconds1 = (); my %Seconds2 = (); my %TotalTime = (); my %Milliseconds = (); my $statement = "File extraction sucessfully completed in 8s 180ms"; my @values = split(' ', $statement); my $numelements = @values; my $time1 = $values[$numelements-2]; my $time2 = $values[$numelements-1]; if ($time1 =~ m/min/) { $time1 =~ s/[^\d.]//g; $Minutes = $time1; $Seconds1 = $Minutes * 60; } else { $time1 =~ s/[^\d.]//g; $Seconds = $time1; } if ($time2 =~ m/ms/) { $time2 =~ s/[^\d.]//g; $Milliseconds = $time2; $Seconds2 = $Milliseconds / 1000 ; } else { $time2 =~ s/[^\d.]//g; $Seconds = $time2; } $TotalTime = $Seconds1 + $Seconds2 + $Seconds; print "Total time taken: $TotalTime seconds \n";
Suggestions are welcome.

Replies are listed 'Best First'.
Re^3: Convert time into seconds
by Random_Walk (Prior) on Apr 24, 2013 at 10:01 UTC

    I am glad you enjoyed it. Perl coding is fun. I do have a couple of suggestions

    suggestion 1: use strict and warnings. These will alert you to dangerous coding practices. They are a great way to learn to write solid code.

    #!/usr/bin/perl use strict; use warnings;

    :-)

    OK here is a version of your code tidied up a bit, compiling under strict and not throwing warnings

    #!/usr/bin/perl use strict; use warnings; # switch one in for testing each case. # # my $statement = "File extraction sucessfully completed in 8s 180ms"; my $statement = "File extraction sucessfully completed in 3min 8s"; # my $statement = "File extraction sucessfully completed in too much t +ime"; my @values = split(/\s+/, $statement); # split on any number/sort of w +hitespace my @time; $time[0] = pop @values; $time[1] = pop @values; # or use and array slice # my @time = @values[-2,-1]; my $seconds = 0; for my $val (@time) { if ($val =~ s/min$//) { $seconds = $seconds + $val * 60; } elsif ($val =~ s/ms$//) { $seconds = $seconds + $val / 1000; } elsif ($val =~ s/s$//) { $seconds = $seconds + $val; } else { print "Warning, strange value in expected time field: $val\n"; exit; } } print "Total time taken: $seconds seconds \n"

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!
      Thanks !