Perl Date and Concatenation

I’m working with a legacy script that needs the date in YYYY,MM,DD format and the original programmer went through some contortions to get MySQL to calculate the date and report it out. It seemed to me that perl should be able to do that easily. In fact, it can.


my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
my $perl_month = $mon + 1;
my $perl_year = $year + 1900;
my $perl_today = "$perl_year,$perl_month,$mday";
my $perl_today2 = ($year + 1900) . "," . ($mon + 1) . "," . $mday;

if ($DEBUG) { print STDOUT "\n Perl thinks today is: $perl_today, $perl_today2  \n"; }

Perl thinks today is: 2019,12,13, 2019,12,13

Perl can do the arithmetic, but you need to put the calculations in parentheses. If you don’t it gets confused and outputs 2020,13. Note that localtime() gives the year as an offset from 1900 and the month starting with January as 0—much like array notation.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.