Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl print current year in 4 digit format

Tags:

perl

how do i get the current year in 4 digit this is what i have tried

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

This prints DBR_ 114\Apr\Failures_input\Failures27Apr.csv

How do I get 2014?

I am using version 5.8.8 build 820.

like image 220
user3360439 Avatar asked Apr 27 '14 13:04

user3360439


Video Answer


4 Answers

use Time::Piece;

my $t = Time::Piece->new();
print $t->year;
like image 110
abra Avatar answered Oct 16 '22 20:10

abra


Move the line:

$year = $year+1900;

To after that call to localtime() and to become:

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
$year = $year+1900;
like image 21
Lee Duhem Avatar answered Oct 16 '22 18:10

Lee Duhem


The best way is to use the core library Time::Piece. It overrides localtime so that the result in scalar context is a Time::Piece object, you can use the many methods that the module supplies on it. (localtime in list context, as you have used it in your own code, continues to provide the same nine-element list.)

The strftime method allows you to format a date/time as you wish.

This very brief program produces the file path that I think you want (I doubt if there should be a space after DBR_?) Note that there is no need to double up backslashes inside a single-quoted string unless it is the last character of the string.

use strict
use warnings;

use Time::Piece;

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

print $path;

output

DBR_2014\Apr\Failures_input\Failures27Apr.csv
like image 6
Borodin Avatar answered Oct 16 '22 20:10

Borodin


One option to get the 4 digit year:

#!/usr/bin/perl

use POSIX qw(strftime);

$year = strftime "%Y", localtime;

printf("year %02d", $year);
like image 5
lagbox Avatar answered Oct 16 '22 20:10

lagbox