从Perl中的DateTime打印年,月和日期

chr*_*003 1 perl datetime

我是Perl的新手,我需要从Perl中的DateTime对象中提取月,日和时间.

以下代码是我目前拥有的代码:

use strict;

use DateTime::Format::Strptime;
my $parser = DateTime::Format::Strptime->new( pattern => "%Y-%m-%dT%H:%M:%SZ", time_zone => 'UTC',
    on_error  => 'croak');
my $date1 = $parser->parse_datetime("2017-10-10T04:21:56Z");
print STDERR "Year: $date1->year()";
Run Code Online (Sandbox Code Playgroud)

我总是得到我的输出:年份:2017-10-10T04:21:56->年().

我究竟做错了什么?或者我应该在双引号之外打印年份?

Dav*_*oss 6

问题是方法调用(或实际上,任何子例程调用)不会在带引号的字符串中展开.你需要在这里使用连接:

print STDERR "Year: " . $date1->year();
Run Code Online (Sandbox Code Playgroud)

或者将多个参数传递给print():

print STDERR "Year: ", $date1->year();
Run Code Online (Sandbox Code Playgroud)

另请注意,print STDERR通常拼写warn(...).

更新:这也值得指出实际发生的事情.当Perl $date1->year()在您引用的字符串中看到它时,它会识别$date1为变量并希望将其扩展为其值.有福的引用的值通常类似于"Class = HASH(0x012345679ABCDEF)"(其中"Class"是类名).但DateTime会覆盖字符串化以显示日期和时间的字符串版本.