Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the optimal way to loop between two dates in Perl?

What is the optimal/clearest way to loop between two dates in Perl? There are plenty of modules on CPAN that deal with such matter, but is there any rule of thumb for iterating between two dates?

like image 334
Spredzy Avatar asked Jul 08 '11 09:07

Spredzy


People also ask

What is Perl loop?

In usual execution, the code is executed sequentially, line-by-line. Loops in Perl are control structures that allow users to run a block of code multiple times.

What is the use of Next in Perl?

next operator in Perl skips the current loop execution and transfers the iterator to the value specified by the next. If there's a label specified in the program, then execution skips to the next iteration identified by the Label.

How do I format a date in Perl?

The Perl POSIX strftime() function is used to format date and time with the specifiers preceded with (%) sign. There are two types of specifiers, one is for local time and other is for gmt time zone.


2 Answers

For everything that uses Date manipulation DateTime is probably the best module out there. To get all dates between two dates with your own increment use something like this:

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

my $start = DateTime->new(
    day   => 1,
    month => 1,
    year  => 2000,
);

my $stop = DateTime->new(
    day   => 10,
    month => 1,
    year  => 2000,
);


while ( $start->add(days => 1) < $stop ) {
    printf "Date: %s\n", $start->ymd('-');
}

This will output:

Date: 2000-01-02
Date: 2000-01-03
Date: 2000-01-04
Date: 2000-01-05
Date: 2000-01-06
Date: 2000-01-07
Date: 2000-01-08
Date: 2000-01-09
like image 189
David Raab Avatar answered Sep 20 '22 05:09

David Raab


These days, most people would recommend using DateTime:

use DateTime;   

my $start = DateTime->new(...); # create two DateTime objects
my $end   = DateTime->new(...);

while ($start <= $end) {
    print $start->ymd, "\n";
    $start->add(days => 1);
}
like image 34
Eugene Yarmash Avatar answered Sep 22 '22 05:09

Eugene Yarmash