10

如何在 Perl 文件中写入当前时间戳?

我制作了一个名为的文件myperl.pl,它将打印当前时间戳。该文件如下所示:

#!/usr/local/bin/perl
@timeData = localtime(time);
print "@timeData\n";

现在我正在尝试将此文件的输出重定向到另一个文本文件。脚本如下:

#!/usr/local/bin/perl
@myscript = "/usr/bin/myperl.pl";
@myfile = "/usr/bin/output_for_myperl.txt";
perl "myscript" > "myfile\n";

运行此程序时,我遇到以下错误:

perl sample_perl_script.pl
String found where operator expected at sample_perl_script.pl line 4, near "perl "myscript""
(你需要预先声明 perl吗?) sample_perl_script.pl line 4, near "perl "myscript"" 的
语法错误
sample_perl_script.pl 由于编译错误而中止。

4

2 回答 2

36

另一个提示。如果你想控制时间戳的格式,我通常会抛出一个像下面这样的子程序。这将返回格式为“20120928 08:35:12”的标量。

sub getLoggingTime {

    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    my $nice_timestamp = sprintf ( "%04d%02d%02d %02d:%02d:%02d",
                                   $year+1900,$mon+1,$mday,$hour,$min,$sec);
    return $nice_timestamp;
}

然后将您的代码更改为:

my $timestamp = getLoggingTime();
于 2012-09-28T19:57:42.703 回答
11

您需要一个文件句柄来写入文件:

#!/usr/local/bin/perl

use strict;
use warnings;

my $timestamp = localtime(time);

open my $fh, '>', '/tmp/file'
   or die "Can't create /tmp/file: $!\n";

print $fh $timestamp;

close $fh;

一些文档:open,学习 Perl

另一种解决方案是一个没有文件句柄的脚本,只是一个打印,然后在命令行上:

./script.pl > new_date_file
于 2012-09-28T17:08:54.010 回答