[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 624
  • Last Modified:

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?
1 Solution
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.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now