I am looking for a Perl script which can give me the last Monday for any specified date.
e.g. For date 2011-06-11, the script should return 2011-06-06
You could also use Time::ParseDate, which understand "last Monday".
A one-liner to maintain Perl's reputation:
perl -MTime::ParseDate -M'POSIX qw(strftime)' -l -e'foreach (@ARGV) { my $now= parsedate( $_); my $e= parsedate( "last Monday", NOW => $now) ; print "$_ : ", strftime "%F", localtime( $e)}' 2011-06-11 2011-06-12 2011-06-13 2011-06-14
And a sane script:
#!/usr/bin/perl
use strict;
use warnings;
use Time::ParseDate; # to parse dates
use POSIX qw(strftime); # to format dates
foreach my $date (@ARGV)
{ my $date_epoch= parsedate( $date) || die"'cannot parse date '$date'\n";
my $monday= parsedate( "last Monday", NOW => $date_epoch); # last Monday before NOW
print "Monday before $date: ", strftime( "%F", localtime( $monday)), "\n"; # %F is YYYY-MM-DD
}
A couple of notes: if the date is a Monday, then you get the previous Monday, which may or may not be what you want, to change that just set NOW to the next day (add 60*60*24, a day, to $date_epoch). Then Time::ParseDate is pretty liberal, it will happily parse 2011-23-38 for example (as 2012-12-09).