Home: Perl Programming Help: Intermediate:
Populate time period dynamically

New User

Apr 11, 2013, 11:25 PM

Views: 1316
Populate time period dynamically

I am generating a report from CSV file. I've been using @time_period array with hard-coded values as shown below. The problem that I am facing is as @time_period reaches its last value and there are still some lines to be processed in CSV file, it show last value stored in array for rest of the lines. I need put in time period with interval of 15 mins that will provide the values dynamically instead of displaying static values. I am sure that there is a way to populate the list dynamically, could someone please point me to that?

#!/usr/bin/perl -w 

use strict;
use warnings;

my $i=0;

my @time_period = ( '09:00 to 09:15',
'09:15 to 09:30',
'09:30 to 09:45',
'09:45 to 10:00',
'10:00 to 10:15',
'10:15 to 10:30',
'10:30 to 10:45');

open(FH, "<some-csv-file") or die("Cannot open file: $!");

while(<FH>) {

print "$time_period[$i]\n";

#logic applied based on contents of csv and printing them

$i += 1; #increasing array index by one, not interested in this approach

Veteran / Moderator

Apr 12, 2013, 1:22 AM

Views: 1312
Re: [r00tuser] Populate time period dynamically

Hmm, perhaps not very clean, but consider the following session under the debugger:

  DB<1> $g = scalar gmtime 32401; 

DB<2> print $g
Thu Jan 1 09:00:01 1970
DB<3> print $1 if $g =~ /(\d\d:\d\d):\d\d/
DB<4> $g = scalar gmtime 32401 + 60*15

DB<5> print $g
Thu Jan 1 09:15:01 1970
DB<6> print $1 if $g =~ /(\d\d:\d\d):\d\d/

As you can see, this way you can generate time intervals of 15 minutes as you need. Something like this:

my $t = 60*60*9 + 1; 
while (<>) {
my $g = scalar gmtime $t;
$t += 60*15 ; # add 15 minutes to $t;
my $timestamp = $1 if if $g =~ /(\d\d:\d\d):\d\d/;
# whatever you want to to with the input

(This post was edited by Laurent_R on Apr 12, 2013, 1:58 AM)

Veteran / Moderator

Apr 12, 2013, 7:00 AM

Views: 1303
Re: [r00tuser] Populate time period dynamically

I'd use the mktime function (from either the POSIX or Date::Calc module) to establish the starting timestamp and then increment it by 15min as needed.