Kittamaru Kittamaru - 3 months ago 11
Perl Question

Perl - How to generate an updating timestamp

I've gotten a decently functioning script going, and am happy with its results so far, thanks in large part to information I've found here.

However, one thing I cannot seem to get right is the timestamp. Currently, I am using this

use POSIX qw/strftime/;
my $timestamp = strftime('%m/%d/%Y %I:%M.%S %p %Z',localtime);


which works well, except that when I call $timestamp, it will always be the same timestamp for all parts of the code (doesn't update at all).

I attempted to remedy this with a subroutine (which I've never done before):

sub GetLoggingTime {
use POSIX qw/strftime/;
my $LoggingTime = strftime('%m/%d/%Y %I:%M.%S %p %Z',localtime);
return $LoggingTime;
}

my $timestamp = GetLoggingTime();

print "$timestamp \n";
sleep(2);
print "$timestamp \n";


obviously the two prints and the sleep are to try and see if it is "updating", which it isn't. Both timestamps print with the same time.

I then tried to invoke the subroutine directly, adding a print within the subroutine and calling it using &GetLoggingTime, but that didn't do anything at all (no output).

I know I'm probably missing something obvious, but I just can't seem to find it. Is there a simple way to get that to work or is there a simple way to get a timestamp that updates in real time as the script progresses?

Thanks in advance!

Answer

You don't need to put the use statement inside your subroutine, that can be placed at the top of your program.

Your code:

my $timestamp = GetLoggingTime();

print "$timestamp \n";
sleep(2);
print "$timestamp \n";

calls GetLoggingTime(), and stores the output inside $timestamp. Which means the value will remain static inside $timestamp. If you want to get the output of the present time each time, you will have to call GetLoggingTime() each time you need an updated value:

my $timestamp = GetLoggingTime();
print "$timestamp \n";
sleep(2);
$timestamp = GetLoggingTime();
print "$timestamp \n";

You can avoid using a variable by concatenating the result of GetLoggingTime() directly to your strings:

print GetLoggingTime() . " \n";
sleep(2);
print GetLoggingTime() . " \n";

or if your time stamp will always require a space and newline, you can include that inside GetLoggingTime()

sub GetLoggingTime {
    return strftime('%m/%d/%Y %I:%M.%S %p %Z',localtime) . " \n";
}