tags:

views:

131

answers:

3

I'm trying to append the integral return value of localtime (in Perl) but I can't seem to avoid it converting the return val to something that looks like this: Sun Jul 26 16:34:49 2009 When I say print localtime I see what I want, but when I say $foo = localtime,""; print $foo; I get the string. I want those digits. I tried $foo = localtime() * 1 but that reverts to 1969 AND gets the string.

Very confusing.

+6  A: 

That string is what localtime returns in a scalar context. It returns

( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime();

in a list context. If you want just the timestamp, use time.

Axeman
that works exactly as I want it. thanks much.
Dr.Dredel
+4  A: 

Perl treats things differently depending on context. In scalar context, localtime returns a string representing the current (local) time. In list context, it returns a list of the various fields that make up a time value.

This problem arises because of the syntax of print.

    * print FILEHANDLE LIST
    * print LIST
    * print

Since print expects a list, this puts localtime in list context, so it returns a list of digits representing the seconds, minutes, hours, and so on, which are then concatenated by the print function. When assigning to a scalar, localtime is in scalar context and returns the string. If you want the concatenation of those digits, you can do something like

my $foo = join '', localtime;
print $foo;

However, perhaps a proper epoch time value would be more useful for whatever you're doing. In that case you can use time instead.

friedo
yeah, I misunderstood what those digits were. I thought it was a millisecond stamp. I realize now it's totally not what I wanted, whereas 'time' is exactly what I need.
Dr.Dredel
+1  A: 

Whenever you think you know what a function does, but it isn't doing that, check the documentation. I frequently check the localtime docs because I can never remember in what order the values come out.

brian d foy