Printing out this week's dates in perl

Posted by ABach on Stack Overflow See other posts from Stack Overflow or by ABach
Published on 2010-05-26T20:26:52Z Indexed on 2010/05/26 20:31 UTC
Read the original article Hit count: 348

Filed under:
|

Hi folks,

I have the following loop to calculate the dates of the current week and print them out. It works, but I am swimming in the amount of date/time possibilities in perl and want to get your opinion on whether there is a better way. Here's the code I've written:

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

use DateTime;

# Calculate numeric value of today and the 
# target day (Monday = 1, Sunday = 7); the
# target, in this case, is Monday, since that's
# when I want the week to start
my $today_dt = DateTime->now;
my $today = $today_dt->day_of_week;
my $target = 1;

# Create DateTime copies to act as the "bookends"
# for the date range
my ($start, $end) = ($today_dt->clone(), $today_dt->clone());

if ($today == $target)
{
  # If today is the target, "start" is already set;
  # we simply need to set the end date
  $end->add( days => 6 );
}
else
{
  # Otherwise, we calculate the Monday preceeding today
  # and the Sunday following today
  my $delta = ($target - $today + 7) % 7;
  $start->add( days => $delta - 7 );
  $end->add( days => $delta - 1 );
}

# I clone the DateTime object again because, for some reason,
# I'm wary of using $start directly...
my $cur_date = $start->clone();

while ($cur_date <= $end)
{
  my $date_ymd = $cur_date->ymd;
  print "$date_ymd\n";
  $cur_date->add( days => 1 );
}

As mentioned, this works - but is it the quickest/most efficient/etc.? I'm guessing that quickness and efficiency may not necessarily go together, but your feedback is very appreciated.

© Stack Overflow or respective owner

Related posts about perl

Related posts about datetime