Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

built in - How do I use Perl's localtime with print to get the timestamp?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

print "$query executed successfully at ", localtime, "
"; # list context
print "$query executed successfully at ",(localtime),"
"; # list context
print "$query executed successfully at ". localtime, "
"; # scalar context
print "$query executed successfully at ".(localtime),"
"; # scalar context

print "$query executed successfully at ", scalar  localtime, "
"; # scalar context
print "$query executed successfully at ", scalar (localtime),"
"; # scalar context

This can be made clearer by splitting up the statements.

my $time = localtime; # scalar context
print "$query executed successfully at $time
";

my @time = localtime; # list context
print "$query executed successfully at @time
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...