Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print Last Months Name

Status
Not open for further replies.

lynxus

ISP
Oct 24, 2006
10
GB
hey guys, I really just cant figure this out.. ( lil new to perl ) :(

Anyway, i have a script that does several things to a database, However i need a dynamic name to print out..

IE:
Rather than

print "September";

I need perl to look at what month is it now. ( October ) then go back one and print that name instead.. IE: September

So summat like
$monthname = some code to do it.

print "$monthname";




Any Ideas out there ?


Cheers
in advace
Graham
 
Stick the months in a hash where the key is the month number, then just reference the value of the month minus one where you need it.

- George
 
using an already offset array is also very easy for this task:

Code:
my @months = qw(Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov);
my $last_month = (localtime())[4];
print $months[$last_month];





- Kevin, perl coder unexceptional!
 
Kevin's solution also avoids the problem of what happens in January...

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
As long as you're using an array, another approach would be to set up the array from Jan..Dec (rather than Dec, Jan..Nov) - then just subtract 1 from the month value that localtime returns.

January is month 0 (index '0' in the array), subtract 1 and you have -1. Since array index '-1' is the last element in the array, you would also get December.
Code:
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my $last_month = (localtime())[4] - 1;
print $months[$last_month];
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top