我使用以下语句来获取当前时间。
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
前两个语句不以日期格式打印当前时间。 第三个陈述仅以日期格式给出正确的输出。
我的理解是第一个在标量上下文中返回一个值,因此返回数字。
然后在第二次打印中我只在列表上下文中使用了localtime,为什么它也给出了数字输出。
答案 0 :(得分:31)
在Perl中编程可能最重要的事情就是上下文。许多内置子例程和运算符的行为取决于上下文。
print "$query executed successfully at ", localtime, "\n"; # list context
print "$query executed successfully at ",(localtime),"\n"; # list context
print "$query executed successfully at ". localtime, "\n"; # scalar context
print "$query executed successfully at ".(localtime),"\n"; # scalar context
print "$query executed successfully at ", scalar localtime, "\n"; # scalar context
print "$query executed successfully at ", scalar (localtime),"\n"; # scalar context
通过分割陈述可以使这更清楚。
my $time = localtime; # scalar context
print "$query executed successfully at $time\n";
my @time = localtime; # list context
print "$query executed successfully at @time\n";
答案 1 :(得分:10)
localtime
的返回值取决于上下文。在列表上下文中,它是一个9元素的列表,而在标量上下文中,它是ctime(3)
值:
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
my $now_string = localtime; # e.g., "Thu Oct 13 04:54:34 1994"
现在,print
为其参数提供了列表上下文。这就是print localtime
从列表中输出数字的原因(默认情况下没有任何分隔符)。您可以使用localtime
连接运算符(如第3条语句中)或使用scalar
强制.
上的标量上下文:
print "".localtime;
print scalar localtime;
答案 2 :(得分:7)
scalar强制标量上下文:
print scalar localtime ();
在第二个例子中,它显然是一个列表上下文,所以你只是连续打印出数字。例如,尝试
print join (":", (localtime));
你会看到用冒号连接的数字。
答案 3 :(得分:4)
第一个和第二个都返回列表上下文中的值,但它们可能不是您所期望的。在当地时间使用parens根本不会做任何有用的事情。但您可以使用以下代码分别获取这些返回的列表项:
@list = ($sec,$min,$hour,$day,$mon,$year_1900,$wday,$yday,$isdst)=localtime;
print join("\n",@list);
答案 4 :(得分:0)
如果您想获得当前时间的时间戳, 你可以使用函数时间()