What is the optimal way to loop between two dates in Perl?
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);
}
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