Getting the last day of last month in perl can be a little tricky but I have just the solution for it.
First you find todays date using my favorite subroutine.

&get_date(0); #0 for number of days in past = today.

Second you take todays date and pass it to &get_date subroutine:

$current_day = $da; # $da is given a value by above subroutine.
&get_date($current_day); # Pass along todays date back to the get_date subroutine.

Now that you’ve passed the current day of month back to get_date, all the date values will be that of last day of last month.
Suppose today is September 7 2010

$yyyy = 2010
$mo = 08
$da = 31

Now lets put it all together.

#!/usr/bin/perl -w
use strict;
use Time::localtime; # &get_date needs this

# Date declarations
my $yyyy;
my $mo;
my $da;

my $current_days;    # Will be used to hold number of days in current month.
my $lastDayofLastMonth; # Variable for last day of the last month

# -----------------------------------------------------------------------
# Main
# -----------------------------------------------------------------------

&get_date_info;

print "Last day of last month was $lastDayofLastMonth \n";  # Will print out the last day of last month.

# -----------------------------------------------------------------------
# Figure last day of last month
# -----------------------------------------------------------------------
sub get_date_info {
    &get_date(0);
    $current_days = $da;
    &get_date($current_days);
    $lastDayofLastMonth = $yyyy . $mo . $da;

}

# -----------------------------------------------------------------------
# get date (my favorate subroutine!)
# -----------------------------------------------------------------------

sub get_date {
   my ($pastno) = @_; #Used to pass value for specific date in past.
   my $pastdate = localtime(time -(86400 * $pastno)); #pastno is # of days in past - set above
   $yyyy = $pastdate->year() + 1900;  # localtime->year() return years since 1900
   $mo = $pastdate->mon() + 1;        # localtime->mon() return 0-11,  Jan. - Dec.
   $da = $pastdate->mday();

   $mo = "0"."$mo"  if ($mo <= 9);
   $da = "0"."$da"  if ($da <= 9);

}
I don’t think this can be any simpler. If you have a much better way of doing this – PLEASE SHARE!

« »