tags:

views:

960

answers:

4

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.

+3  A: 

scalar forces scalar context:

print scalar localtime ();

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

 print join (":", (localtime));

and you'll see the numbers joined with a colon.

Kinopiko
+2  A: 

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:

@list = ($sec,$min,$hour,$day,$mon,$year_1900,$wday,$yday,$isdst)=localtime;
print join("\n",@list);
Mike
+4  A: 

See perldoc localtime:

In scalar context, localtime() returns the ctime(3) value:

$now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"

You have scalar context only in the third statement. In other statements, all list items are printed w/o separator. You can set the $, variable to some value before printing to have them separated.

eugene y
+5  A: 

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, "\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

This can be made clearer by splitting up the statements.

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

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