dragonchild has asked for the wisdom of the Perl Monks concerning the following question:

Reading the pages for localtime, there are two contexts - the scalar and the list contexts. Is there a pre-defined way of converting between the two? Basically, I'd like to be able to store in a file the scalar return (a nicely formatted string), but be able to do calculations with the list return (a nice series of numbers).
  • Comment on Converting between localtime scalar and list contexts

Replies are listed 'Best First'.
Re: Converting between localtime scalar and list contexts
by bikeNomad (Priest) on Jun 05, 2001 at 21:20 UTC
    Um, why not just call it in both contexts? Just get the current time using time(), then pass it to localtime:

    my $time = time; my $ctime = localtime($time); my @timeArray = localtime($time);
    Or, see the POSIX module's strftime() time formatting routine that would allow you to take @timeArray above and format it however you wish.
      A warning on doing this kind of thing. Notice that bikeNomad determined the time only once; the other time values are based on it. That's very important 'cause if you do it this way:
      my $time = time; my $ctime = localtime; my @timeArray = localtime;
      which might seem more "natural", you leave yourself open to a very subtle and obsure bug: What if the second changes between one of those calls? It might look like an "off-by-one" error, but it only happens "sometimes". Maybe nothing serious happens. But what if midnight occurs between one of those calls? Depending on what you're doing with @timeArray and $ctime you will get inconsistent results. This could hurt. I have seen it happen.

      Have fun,
      Carl Forde

Re: Converting between localtime scalar and list contexts
by suaveant (Parson) on Jun 05, 2001 at 21:24 UTC
    You have to call it twice, or generate your own scalar version from the list output. What happens is, if you call localtime in a string context, perl knows this and localtime generates a string, whereas if you call it in list context, you get the raw list output. There is a module called Timelocal that lets you convert a date to seconds since the Epoch, but really the best thing to do probably is to store the output of time() for the time you want, and then feed it through localtime like so
    $str = localtime($storedtime); @date = localtime($storedtime);

                    - Ant

Re: Converting between localtime scalar and list contexts
by dragonchild (Archbishop) on Jun 05, 2001 at 22:09 UTC
    I found Date::Format and used the strftime() function to convert from list to string. However, I would very much like to be able to convert from the string to the list without writing my own function.
      Look at Date::Parse which will parse a time/date string.