Alex Rivera | Logout

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

Asked 2010-04-07T11:31:36.833
24

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.

Edit
Report

1 Answer

10

The return value of localtime depends on the context. In list context it is a 9-element list, while in scalar context it is a ctime(3) value:

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
my $now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"

Now, print provides list context for its arguments. That's why print localtime outputs the numbers from the list (without any separator by default). You can force scalar context on localtime using either the . concatenation operator (like in your 3rd statement) or using scalar:

print "".localtime;
print scalar localtime;
answered 2010-04-07T12:05:59.210

Your Answer