Reputation: 15
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!
Upvotes: 1
Views: 603
Reputation: 1562
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";
}
Upvotes: 6
Reputation: 69264
You can achieve what you want using tied variables. But note that tie
ing is a rather esoteric corner of Perl and using it will slow down your program.
I was going to demonstrate by writing a simple tied timestamp example. But it seems that Tie::Scalar::Timestamp already exists.
Upvotes: 1