如何使用 Perl 的本地时间和 print 来获取时间戳?
我使用以下语句来获取当前时间。
print "$query executed successfully at ",localtime;
print "$query executed successfully at ",(localtime);
print "$query executed successfully at ".(localtime);
输出
executed successfully at 355516731103960
executed successfully at 355516731103960
executed successfully at Wed Apr 7 16:55:35 2010
前两个语句不以日期格式打印当前时间。 第三条语句仅以日期格式提供正确的输出。
我的理解是第一个是在标量上下文中返回一个值,因此它返回数字。
然后在第二次打印中,我仅在列表上下文中使用本地时间,为什么它也给出数字输出。
I have used the following statements to get the current time.
print "$query executed successfully at ",localtime;
print "$query executed successfully at ",(localtime);
print "$query executed successfully at ".(localtime);
Output
executed successfully at 355516731103960
executed successfully at 355516731103960
executed successfully at Wed Apr 7 16:55:35 2010
The first two statements are not printing the current time in a date format.
Third statement only giving the correct output in a date format.
My understanding is the first one is returning a value in scalar context, so it is returning numbers.
Then in the second print I used localtime in list context only, why it's also giving number output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
也许在 Perl 编程中你可以学到的最重要的东西就是上下文。许多内置子例程和运算符的行为根据上下文而有所不同。
通过拆分语句可以使这一点变得更清楚。
Perhaps the most important thing you can learn for programming in Perl, is context. Many built-in subroutines, and operators, behave differently depending on the context.
This can be made clearer by splitting up the statements.
localtime
的返回值取决于上下文。在列表上下文中,它是一个 9 元素列表,而在标量上下文中,它是一个ctime(3)
值:现在,
print
为其参数提供列表上下文。这就是为什么print localtime
从列表中输出数字(默认情况下不带任何分隔符)。您可以使用.
连接运算符(如第三条语句中所示)或使用标量
:The return value of
localtime
depends on the context. In list context it is a 9-element list, while in scalar context it is actime(3)
value:Now,
print
provides list context for its arguments. That's whyprint localtime
outputs the numbers from the list (without any separator by default). You can force scalar context onlocaltime
using either the.
concatenation operator (like in your 3rd statement) or usingscalar
:标量 强制标量上下文:
在第二个示例中,它显然是一个列表上下文,因此您只是获得连续数字的打印输出。例如,尝试一下
,您将看到用冒号连接的数字。
scalar forces scalar context:
In the second example, it's clearly a list context so you're just getting a printout of the numbers in a row. For example, try
and you'll see the numbers joined with a colon.
第一个和第二个都返回列表上下文中的值,但它们可能不是您所期望的。在当地时间附近使用括号根本不会做任何有用的事情。但是您可以使用以下代码单独获取这些返回的列表项:
Both the first and second return the values in the list context but they are probably not what you would expect. The use of parens around localtime simply won't do anything useful. But you can use the following code to get those returned list items separately:
如果你想获取当前时间的时间戳,
你可以只使用函数 time()
If you want to get the timestamp of the current time,
you can just use function time()