Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

How to add minutes with seconds?

by gube (Parson)
on Mar 15, 2006 at 09:59 UTC ( [id://536796]=perlquestion: print w/replies, xml ) Need Help??

gube has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

In an array i am having song timings with minutes:seconds, i need total minutes and seconds stored in the array. Please give me some links or sample codes.

For eg : @a = qw(1:08 2:05); Total I need : 3:13

Thanks in advance.

Replies are listed 'Best First'.
Re: How to add minutes with seconds?
by Corion (Patriarch) on Mar 15, 2006 at 10:04 UTC

    Traditionally, the way is to convert your minutes and seconds into seconds, then add the seconds, and then convert it back. This is easy if you use split to split the number into the "minutes" and "seconds" part, the rest then is simple application of multiplication, addition and division. So, what code have you written already?

      ok thanks for your easy way corion, i planned to do using Time::Piece module.

Re: How to add minutes with seconds?
by prasadbabu (Prior) on Mar 15, 2006 at 10:25 UTC

    Hi gube, as Corion suggested you can do it simply without using module. Here is my try, but it can be still simplified.

    use strict; my @a = qw(1:08 2:53 1:00); my ($tt, $mins, $sec); for my $t (@a) { my ($m, $s) = split /:/, $t; my $tm = $m*60; $tt = $tt + $tm + $s; } $sec = sprintf ("%02d", $sec = $tt%60); #seconds $mins = int($tt/60); #minutes print "$mins:$sec";

    Prasad

Re: How to add minutes with seconds?
by davidrw (Prior) on Mar 15, 2006 at 13:51 UTC
Re: How to add minutes with seconds?
by smokemachine (Hermit) on Mar 15, 2006 at 16:17 UTC
    perl -e 'my @a = qw(1:08 2:53 1:00); foreach(@a){($min, $sec)=split /: +/;$time+=($min*60)+$sec}; print $time=int($time/60).":".(sprintf "%.2 +d", $time%60)."\n"'

      I believe you can further reduce the code to:

      perl -e 'my @a = qw(1:08 2:53 1:00); foreach(@a){($min, $sec)=split /: +/;$time+=( +$min*60)+$sec}; print int($time/60).":".(sprintf "%.2d", $time%60)."\ +n"'

      It only saves six keystrokes; however, I do love the economy of your code.

      Mike

        perl -e 'for (@ARGV) { /(d+):(\d+)/; $time += $1*60 + $2 } printf "%d:%.2d\n", $time/60, $time%60' 1:08 2:53 1:00

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://536796]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-03-29 06:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found