打印时如何将 localtime() 保留为 int?
我试图附加本地时间的积分返回值(在 Perl 中),但我似乎无法避免它将返回值转换为如下所示的内容:Sun Jul 26 16:34:49 2009 当我说打印本地时间时我看到了我想要的东西,但是当我说 $foo = 当地时间,""; 打印 $foo; 我得到了字符串。 我想要那些数字。 我尝试了 $foo = localtime() * 1 但会恢复到 1969 年并获取字符串。
很混乱。
I'm trying to append the integral return value of localtime (in Perl) but I can't seem to avoid it converting the return val to something that looks like this: Sun Jul 26 16:34:49 2009
When I say print localtime I see what I want, but when I say
$foo = localtime,""; print $foo; I get the string.
I want those digits. I tried $foo = localtime() * 1 but that reverts to 1969 AND gets the string.
Very confusing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该字符串是
localtime
在标量上下文中返回的内容。 它在列表上下文中返回。 如果您只需要时间戳,请使用
time
。That string is what
localtime
returns in a scalar context. It returnsin a list context. If you want just the timestamp, use
time
.Perl 根据上下文对事物进行不同的处理。 在标量上下文中,
localtime
返回表示当前(本地)时间的字符串。 在列表上下文中,它返回组成时间值的各个字段的列表。出现此问题的原因是
print
的语法。由于
print
需要一个列表,因此会将localtime
放入列表上下文中,因此它返回表示秒、分钟、小时等的数字列表,然后将这些数字连接起来通过print
函数。 当分配给标量时,localtime
位于标量上下文中并返回字符串。 如果您想要连接这些数字,您可以执行类似的操作但是,也许正确的纪元时间值对于您正在做的任何事情都更有用。 在这种情况下,您可以使用
时间
来代替。Perl treats things differently depending on context. In scalar context,
localtime
returns a string representing the current (local) time. In list context, it returns a list of the various fields that make up a time value.This problem arises because of the syntax of
print
.Since
print
expects a list, this putslocaltime
in list context, so it returns a list of digits representing the seconds, minutes, hours, and so on, which are then concatenated by theprint
function. When assigning to a scalar,localtime
is in scalar context and returns the string. If you want the concatenation of those digits, you can do something likeHowever, perhaps a proper epoch time value would be more useful for whatever you're doing. In that case you can use
time
instead.每当您认为您知道某个函数的作用,但实际上它并没有这样做时,请检查文档。 我经常检查 localtime 文档,因为我永远记不起值的顺序。
Whenever you think you know what a function does, but it isn't doing that, check the documentation. I frequently check the localtime docs because I can never remember in what order the values come out.