【问题标题】:Cannot print System Local Time with use Time::localtime function in Perl无法在 Perl 中使用 Time::localtime 函数打印系统本地时间
【发布时间】:2014-08-01 05:33:49
【问题描述】:

我编写了一个 Perl 脚本来从配置文件中获取特定信息

use Time::localtime;
my $date_string = ctime(stat($filepath)->mtime);
print "$date_string\t";

上面的代码打印了文件的最后修改时间和日期,但问题是我用下面的函数无法打印报告生成时间

my $time = localtime; # scalar context
print "executed successfully at $time\n";

我收到以下错误

executed successfully at Time::tm=ARRAY(0x336e048)

【问题讨论】:

    标签: perl time


    【解决方案1】:

    Time::localtime 模块默认导出覆盖核心 localtime() 函数,将其替换为返回“Time::tm”对象的版本

    所以如果你想使用核心 Perl 本地时间,这样写:

    my $time = CORE::localtime;
    

    【讨论】:

      【解决方案2】:

      在您的代码中,您会获得对数组的引用。所以引用被打印出来了。

      使用

      my $time = scalar(CORE::localtime); # scalar context
      

      更多信息到scalarfunction你可以找到here

      说明
      此函数强制 EXPR 的评估在 标量上下文,即使它通常在列表上下文中工作。

      语法 以下是此函数的简单语法:标量 EXPR 返回值 此函数返回标量

      【讨论】:

      • 即使现在我收到错误Time::tm=ARRAY(0x359eb70)
      • 谢谢 Jens,使用 scalar(CORE::localtime) 而不是仅仅使用 CORE::localtime 有什么特别的优势
      • 是的CORE::LOcation gives you a reference to an array, so if you only print the result, you print the reference of the array. scalar`给你标量上下文,所以你得到字符串。
      • 不,这里对scalar 的显式调用是冗余localtime 将自动检测它是否用于标量或列表上下文。通过将其分配给 $time,它会在标量上下文中自动解释。
      猜你喜欢
      • 2018-12-31
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 2013-02-13
      相关资源
      最近更新 更多