perl以4位数字格式打印当前年份

use*_*439 6 perl

我如何得到4位数的当前年份这是我试过的

 #!/usr/local/bin/perl

 @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
 @days = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
 $year = $year+1900;
 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
 print "DBR_ $year\\$months[$mon]\\Failures_input\\Failures$mday$months[$mon].csv \n";
Run Code Online (Sandbox Code Playgroud)

这打印 DBR_ 114\Apr\Failures_input\Failures27Apr.csv

我如何获得2014年?

我正在使用版本5.8.8 build 820.

abr*_*bra 11

use Time::Piece;

my $t = Time::Piece->new();
print $t->year;
Run Code Online (Sandbox Code Playgroud)


Lee*_*hem 10

移动线:

$year = $year+1900;
Run Code Online (Sandbox Code Playgroud)

在那之后召唤localtime()并成为:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year = $year+1900;
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考 - 你可以说'我的年份= 1900 +(当地时间)[5];` (8认同)

Bor*_*din 6

最好的方法是使用核心库Time::Piece。它覆盖localtime以便标量上下文中的结果是一个Time::Piece对象,您可以使用模块在其上提供的许多方法。(localtime在列表上下文中,正如您在自己的代码中使用的那样,继续提供相同的九元素列表。)

strftime方法允许您根据需要格式化日期/时间。

这个非常简短的程序生成我认为你想要的文件路径(我怀疑后面是否应该有一个空格DBR_?)请注意,除非它是字符串的最后一个字符,否则不需要在单引号字符串中加倍反斜杠.

use strict
use warnings;

use Time::Piece;

my $path = localtime->strftime('DBR_%Y\%b\Failures_input\Failures%m%d.csv');

print $path;
Run Code Online (Sandbox Code Playgroud)

输出

DBR_2014\Apr\Failures_input\Failures27Apr.csv
Run Code Online (Sandbox Code Playgroud)


lag*_*box 5

获得 4 位数年份的一种选择:

#!/usr/bin/perl

use POSIX qw(strftime);

$year = strftime "%Y", localtime;

printf("year %02d", $year);
Run Code Online (Sandbox Code Playgroud)