Perl - 将localtime的输出存储到哈希中

时间:2014-03-19 14:59:57

标签: perl hashmap localtime

在perl中,我可以使用以下命令序列获得当前秒数:

my @time = ($sec,$min,$hour,$day,$mon,$year_1900,$wday,$yday,$isdst)=localtime;
print $time[0]

有没有相当于此但使用哈希?所以可以输入这样的内容:

print $time{"sec"} 

我试过了:

my %time= ("sec","min","hour","day","mon","year_1900","wday","yday","isdst")=localtime;
print $time{"sec"}

但它以跟随错误结束:

Can't modify constant item in list assignment at -e line 1, near "localtime;"
Execution of -e aborted due to compilation errors.

由于

3 个答案:

答案 0 :(得分:7)

您可以使用Time::Piece

将其存储在对象中,而不是将所有内容都存储在哈希中
#!/usr/bin/perl

use strict;
use warnings;

use Time::Piece;

my $t = localtime;
print $t->sec;

Time::Piece可以进行日期数学运算,比较,解析和输出,使其比简单哈希更灵活。

答案 1 :(得分:3)

您可以使用hash slice

my %time;
@time{"sec","min","hour","day","mon","year_1900","wday","yday","isdst"} = localtime;
# or shorter
# @time{qw(sec min hour day mon year_1900 wday yday isdst)} = localtime;

print $time{"sec"};

答案 2 :(得分:2)

有一些标准 Perl模块可以帮助您。

第一个是Time::localtime。您可以使用名称方法替换内部 localtime命令,以访问各个时间段:

use strict;           # Always
use warnings;         # Always
use feature qw(say);  # An improved version of the print command

use Time::localtime

my $time = localtime; # A Time::Tm object, not your standard localtime command

say $time->sec;       # Prints the seconds

这不是你所要求的 hash ,但是你可以看到它大大改善了localtime提供的各种部分的访问方式,这种方式几乎就像一个哈希值。

您还可以看到使用say,就像print一样,除了您最后不需要那个讨厌的\n(就像您在示例中忘记的那样)。< / p>


将事情带到下一步......

另一个不错的标准模块称为Time::Piece。它提供了更简单的方法来解析时间并显示它。

use strict;           # Always
use warnings;         # Always
use feature qw(say);  # An improved version of the print command

use Time::Piece

my $time =  localtime;
say $time->sec;       # Prints the seconds. Looks pretty much the same

#
# But now look!
#

say $time->ymd;       # Prints the time as YYYY-MM-DD
say $time->ymd("/");  # Prints the time as YYYY/MM/DD
say $time->mdy("/");  # Prints the time as MM/DD/YYYY
say $time->month;     # Prints the name of the month
say $time->cdate;     # Prints date and time as a string

我更喜欢Time::Piece,因为它具有灵活性,并且易于初始化不是当前时间的日期。如果您有日期/时间的字符串,并且可以对其进行描述,则可以轻松创建可以操作的新Time::Piece日期/时间对象。


Perl程序员所遗漏的许多东西之一就是标准Perl模块的聚宝盆,这些模块几乎包含在每个Perl发行版中。这些模块不需要下载或安装。它们存在于几乎任何具有特定Perl版本的计算机上。

您可以将File::Copy用于丢失的文件复制命令。您可以将File::Basename用于缺少basenamedirname命令。您可以使用Perl附带的数百个模块,让您的生活更轻松。参观标准的Perl文档,并使用它。