Converting the hh24:mm format into seconds since midnight allows for greater simplification and modularisationg of the code.
use strict;
use Data::Dumper;
#################################################
#converts a string hh24:mm into seconds equivalent since midnight
sub convert_to_seconds {
my $time = shift;
my ($hours, $minutes) = split ':', $time;
return $hours * 3600 + $minutes * 60;
}
#################################################
#converts a seconds since midnight into hh24:mm format
sub convert_to_hh24mm {
my $time = shift;
my $hours = int ($time / 3600);
my $minutes = ($time % 3600) / 60;
return sprintf("%02d:%02d", $hours, $minutes);
}
#################################################
#takes a begin and end time (in seconds since midnight)
#and an interval (in seconds as well) as arguments
sub generate_intervals {
my ($begin, $end, $interval) = @_;
my @intervals;
while ($end > $begin) {
push @intervals, $begin;
$begin += $interval;
}
return @intervals;
}
#################################################
# M A I N
#
my $begintime = '18:20';
my $endtime = '22:30';
my $interval = 15;
my @intervals = generate_intervals( convert_to_seconds($begintime), co
+nvert_to_seconds($endtime), $interval * 60);
foreach (@intervals){
print Dumper(convert_to_hh24mm($_) );
}
This outputs :
E:\>perl -w test.pl
$VAR1 = '18:20';
$VAR1 = '18:35';
$VAR1 = '18:50';
$VAR1 = '19:05';
$VAR1 = '19:20';
$VAR1 = '19:35';
$VAR1 = '19:50';
$VAR1 = '20:05';
$VAR1 = '20:20';
$VAR1 = '20:35';
$VAR1 = '20:50';
$VAR1 = '21:05';
$VAR1 = '21:20';
$VAR1 = '21:35';
$VAR1 = '21:50';
$VAR1 = '22:05';
$VAR1 = '22:20';
Jorg "Do or do not, there is no try" -- Yoda
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|