Issue with localtime function

I had written a perl script to use the localtime function to get the year, date, month, etc. I am a novice in perl so if there are better ways of doing this, bare with me. I'm working on a windows XP machine with Cygwin.

$date=(join'-',(split/ /,localtime)[1,2,4]);
$year = (join'-', (split/ /,localtime)[4]);
print "Date: $date\n";      # printed "Date: May-31-2006"
print "Year: $year\n";      # printed "Year: 2006"

This worked fine last week. But, today when I was runing the script it was not working. After a little debugging I had to change the above to below to get the same results:

$date=(join'-',(split/ /,localtime)[1,3,5]);
$year = (join'-', (split/ /,localtime)[5]);
print "Date: $date\n";      # printed "Date: Jun-5-2006"
print "Year: $year\n";      # printed "Year: 2006"

Why did this change? what am I missing?
Who is Participating?
TintinConnect With a Mentor Commented:
use POSIX 'strftime';
print strftime("%b-%d-%Y\n",localtime);
you should read "perldoc -tf localtime" and "perldoc POSIX" to be sure that you will understand that in future
(split' ',localtime)
may have been closer to what you intended originally.
But using localtime in list contex instead of scalar context as the others have suggested is a better way to do it.
And even if you use (split' ',localtime) it is not good practice to call localtime twice to get different parts of a date becase the date may change between calls, which could make your parts inconsistent.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.