Perl - 如何生成更新时间戳

Kit*_*aru 1 perl timestamp real-time subroutine

我已经得到了一个功能正常的脚本,并且对它到目前为止的结果感到满意,这在很大程度上要归功于我在这里找到的信息.

但是,我似乎无法做到的一件事是时间戳.目前,我正在使用它

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

哪个效果很好,除了当我调用$ timestamp时,它总是与代码的所有部分相同的时间戳(根本不更新).

我尝试用子程序(我以前从未做过)来解决这个问题:

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";
Run Code Online (Sandbox Code Playgroud)

显然,两个印刷品和睡眠是试图看它是否"更新",但事实并非如此.两个时间戳都打印在同一时间.

然后我尝试直接调用子例程,在子例程中添加一个打印并使用&GetLoggingTime调用它,但是根本没有做任何事情(没有输出).

我知道我可能错过了一些明显的东西,但我似乎无法找到它.是否有一种简单的方法可以使其工作,或者是否有一种简单的方法来获取随着脚本的进展而实时更新的时间戳?

提前致谢!

Dra*_*oan 6

您不需要将use语句放在子例程中,该子例程可以放在程序的顶部.

你的代码:

my $timestamp = GetLoggingTime();

print "$timestamp \n";
sleep(2);
print "$timestamp \n";
Run Code Online (Sandbox Code Playgroud)

调用GetLoggingTime(),并将输出存储在里面$timestamp.这意味着价值将在内部保持静止$timestamp.如果您希望每次都获得当前时间的输出,则GetLoggingTime()每次需要更新值时都需要调用:

my $timestamp = GetLoggingTime();
print "$timestamp \n";
sleep(2);
$timestamp = GetLoggingTime();
print "$timestamp \n";
Run Code Online (Sandbox Code Playgroud)

您可以通过将结果GetLoggingTime()直接连接到字符串来避免使用变量:

print GetLoggingTime() . " \n";
sleep(2);
print GetLoggingTime() . " \n";
Run Code Online (Sandbox Code Playgroud)

或者如果你的时间戳总是需要一个空格和换行符,你可以把它包括在里面 GetLoggingTime()

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