Printing the date and time in a Perl script

I find it useful to print out the data and time after each step when running a long Perl script so that I can keep a check on the progress. If a step only takes a few seconds when it is expected to take much longer then it is a good indication of an error. The date and time also serve as a useful historical log of when a script was executed.

By adding a Perl subroutine at the end of the script, each call of the date and time can be made with a call to the subroutine, clock(). Here is an example code that prints a line of text followed by the date and time.


#!/usr/bin/perl

print "The date and time is:\n";
# call the clock subroutine
clock();

# the clock subroutine
sub clock {
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
my @weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
my $year = 1900 + $yearOffset;
my $theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";
print "*** $theTime ***\n\n";
} 

The output of the script is:

The date and time is:
*** 16:13:7, Tue May 3, 2016 ***

Wrapping the date and time with three asterisks allows me to quickly search for the end of each step in a large log file.

Unknown's avatar

About rdbagnall

PhD human medical genetics | Human molecular genetics research | Bioinformatics
This entry was posted in Perl and tagged . Bookmark the permalink.

Leave a comment