【问题标题】:How to write the current timestamp in a Perl file?如何在 Perl 文件中写入当前时间戳?
【发布时间】:2012-09-20 14:14: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 示例_perl_script.pl
在 sample_perl_script.pl 第 4 行,“perl”myscript“”附近的操作员预期的位置找到字符串
(您需要预先声明 perl 吗?)
sample_perl_script.pl 第 4 行的语法错误,靠近 "perl "myscript""
由于编译错误,sample_perl_script.pl 的执行被中止。

【问题讨论】:

    标签: perl


    【解决方案1】:

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

    #!/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;
    

    一些文档:openLeaning Perl

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

    ./script.pl > new_date_file
    

    【讨论】:

    • 感谢您编辑我的错误;)(错误的 URL)Leaning Perl:由 ikegami 添加。
    • 还将其更改为在标量上下文中调用localtime(因为程序输出了一些无用的东西)并向open添加了错误检查。
    • “Leaning Perl”听起来像是一本相当歪曲的书。
    • 非常感谢..它起作用了..我只在 printf 行中添加了换行符。
    【解决方案2】:

    另一个提示。如果你想控制时间戳的格式,我通常会抛出一个像下面这样的子程序。这将返回格式为“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();
    

    【讨论】:

    • 这个游戏我最近尝试的时候给我一个日期字符串“19000100 00:00:25921516”。这是因为这是一个旧答案,不再适用吗?
    • @Brady:在此处按预期工作20151012 22:13:39(win32 上的 perl 5.18.2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 2017-07-07
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多