Creating a date (without time) in perl

I have a perl script that automatically runs on Mondays.
I need to have it create a variable for last Monday's date thru that Sunday's date.

example: 04-01-2011 thru 04-08-2011

Its reporting numbers for the previous week beginning with Monday and ending on Sunday. So i dont have to go in each week and manually enter the date range in before the script runs.
I no nothing about perl except that the script is in perl.

I'm not sure how wise it is for you to modify a perl script if you literally know nothing about perl. But here is a way to generate those dates:

$
$ date
Thu Apr 14 17:30:28 EDT 2011
$ cat range
#! /usr/bin/perl -w

@d=localtime (time() - (60*60*24*7) );
printf "%02d-%02d-%4d\n", $d[4]+1,$d[3],$d[5]+1900;
@d=localtime (time() - (60*60*24) );
printf "%02d-%02d-%4d\n", $d[4]+1,$d[3],$d[5]+1900;

$ ./range
04-07-2011
04-13-2011
$

Now that I posted my script, the perl experts will come around and show how it's really done. :stuck_out_tongue:

and that will automatically change the range each week?

Yep. time() - (60*60*24*7) That says take the current time and then back up 7 days.

Of course, you must run script on the monday to get mon-sun of Previous week. If, for example, you dont run the program until 1am on Tue you will get dates for Tue(last week) to Mon(yesterday).

Slight change to always give MON thru SUN dates:

#!/usr/bin/perl
@d=localtime( time() );
@e=localtime(time() - (24*3600*$d[6]) ) ;
@s=localtime(time() - (24*3600*($d[6]+6)) ) ;
printf("%02d-%02d-%4d\n", $s[4]+1, $s[3], $s[5]+1900);
printf("%02d-%02d-%4d\n", $e[4]+1, $e[3], $e[5]+1900);

thank you both. I can use either because they do exactly what I need.

You're awesome!

---------- Post updated at 03:52 PM ---------- Previous update was at 07:50 AM ----------

one more thing, how would I make that printf statement a variable?
That way I can just call the variable and not use that long string...

Not sure I understand the request, but maybe....

$ cat range
#! /usr/bin/perl -w

@d=localtime (time() - (60*60*24*7) );
$start = sprintf "%02d-%02d-%4d\n", $d[4]+1,$d[3],$d[5]+1900;
@d=localtime (time() - (60*60*24) );
$end = sprintf "%02d-%02d-%4d\n", $d[4]+1,$d[3],$d[5]+1900;


print "start = ", $start;
print "end = ", $end;

$
$
$
$
$ ./range
start = 04-08-2011
end = 04-14-2011
$
1 Like

that was it. you got it. I messed with it but was typing the print statement wrong.
thanks again/