Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl sub routine for getting a range of dates

Is there a perl routine that I can utilize that would do the following? I'm looking for a good example.

I want to be able to print out a list of days based on a range.

As a parameter I want to be able to do something like: ./myperlscript -r 20110630 20110731 (as an example where -r = range).

So basically, if I can put (2) dates in this format as inputs and print me those days.

20110630
20110701
20110702
...
..
like image 558
jdamae Avatar asked Nov 18 '25 09:11

jdamae


1 Answers

This should get you started. You probably want to add some input validation (ie making sure that the elements of @ARGV are formatted correctly and that the first represents a date smaller than the second, etc, etc...).

use strict;
use warnings;
use DateTime;

unless(@ARGV==2)
{
    print "Usage: myperlscript first_date last_date\n";
    exit(1);
}

my ($first_date,$last_date)=@ARGV;

my $date=DateTime->new(
{
  year=>substr($first_date,0,4),
  month=>substr($first_date,4,2),
  day=>substr($first_date,6,2)
});


while($date->ymd('') le $last_date)
{
  print $date->ymd('') . "\n";
  $date->add(days=>1);
}

ETA: In case it isn't clear what's going on, we create $date as a DateTime object, parsing the year, month, and day that were given in $first_date. Then, we keep printing out the year, month, and day without separators ($date->ymd('')) and increase $date by one day until we're at $last_date.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!