Great stuff!
It's a dozen plus years after this was written and it's still useful. There's a subtle bit introduced at the very end that should maybe be emphasized: these are DateTime objects we're dealing with, and the scalar variables are references to the underlying object, which can lead to some confusion if you let that fact slip your mind.
Consider the bit about math with dates at the end:
my $dt1 = DateTime->now();
my $dt2 = $dt1->clone->subtract( weeks => 1);
Miss the ->clone bit and you've got two references to the same DateTime object, one week subtracted from the original $dt1 value. Probably not what you had in mind.
Imagine expecting the following to DWIM:
#!/usr/bin/perl -w
use strict;
use DateTime;
my ($start, $end, @dates);
$start = DateTime->new(day => 1, month => 1, year => 2017);
$end = DateTime->new(day => 31, month => 1, year => 2017);
while ($start <= $end) {
# Skip weekends
if ($start->day_of_week() > 5) {
push(@dates, $start);
}
$start = $start->add(days => 1);
}
for (@dates) {
print $_, $/;
}
See it? I've forgotten to clone my $start variable as I push it onto my stack. This code produces:
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
2017-02-01T00:00:00
All I needed to do was push(@dates, $start->clone()); and then I see what I meant:
2017-01-02T00:00:00
2017-01-03T00:00:00
2017-01-04T00:00:00
2017-01-05T00:00:00
2017-01-06T00:00:00
2017-01-09T00:00:00
2017-01-10T00:00:00
2017-01-11T00:00:00
2017-01-12T00:00:00
2017-01-13T00:00:00
2017-01-16T00:00:00
2017-01-17T00:00:00
2017-01-18T00:00:00
2017-01-19T00:00:00
2017-01-20T00:00:00
2017-01-23T00:00:00
2017-01-24T00:00:00
2017-01-25T00:00:00
2017-01-26T00:00:00
2017-01-27T00:00:00
2017-01-30T00:00:00
2017-01-31T00:00:00
I hope this helps someone else avoid a similar problem in the future -- even a dozen years from now :)
-
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.