Click to See Complete Forum and Search --> : simple perl text parsing question


mjs111
05-08-2007, 06:41 PM
If I have a text file with a list of times in hours:minutes:seconds format:

0:08:31
0:08:27
0:08:28

how can I automate turning that list into seconds? Ex. parse numbers before first colon and multiply by 3600, parse next set of numbers before second colon and multiply by 60 and add to first number, parse last numbers and add to first number, and generate a list that looks like:

511
507
508

Thanks,

Mike

aj_nsc
05-08-2007, 07:47 PM
this is how i'd do it, some might call me old fashioned.


#!/usr/bin/perl

my @timesOriginal;
my @timesInSeconds;

open(TIMES, "times.txt");
while(<TIMES>) {
chomp($_);
push(@timesOriginal,$_);
}
close(TIMES);


foreach $time (@timesOriginal) {
@hms = split(":",$time);
$totalSeconds = ($hms[0]*3600)+($hms[1]*60)+$hms[2];
push(@timesInSeconds,$totalSeconds);
}

open(NEWTIMES, ">newtimes.txt");
foreach $time (@timesInSeconds) {
print NEWTIMES "$time\n";
}
close(NEWTIMES);


This, of course, puts all your converted times in a new file called newtimes.txt You can fiddle with my script and have them written back into the original file.

Jeff Mott
05-08-2007, 08:23 PM
This ought to do the trick.
use strict;
use warnings FATAL => 'all';

use Tie::File;
use Fcntl ':flock';

my $timesObj = tie(my @times, 'Tie::File', 'times.txt') or die $!;
$timesObj->flock(LOCK_EX) or die $!;
$timesObj->defer();

for (@times) {
my($hours, $minutes, $seconds) = split(/:/, $_);
$_ = $hours * 3600 + $minutes * 60 + $seconds;
}

mjs111
05-08-2007, 08:34 PM
Thanks! Works perfectly.

Mike