Optimizing Perl code (localtime)


While updating some Perl code I wrote quite some time back, I came across the following:

my ($sec, $min, $hour, $day, $month, $year, $wd, $day, $dst) = localtime(time); print $year + 1900 . " “;

This code is rather wasteful, especially when the program only needs the year. A much simpler solution is to put the localtime() result into array context, and index into it:

$ year = (localtime)[5] + 1900;
print “$year “;

I am currently reading two Perl books, and it amazes me just how versatile Perl is!

This article was posted by Matty on 2005-09-23 20:51:00 -0400 -0400