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?
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.
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.
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.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With