in reply to Re: Time to seconds
in thread Time to seconds

A suggestion:
my @time_values = qw [ d h m s ]; my %time_value = ( d => 86400, h => 3600, m => 60, s => 1 );
The array is not necessary, since it can be generated from keys %time_value. That way you don't have to keep the two data structures in sync.

—John

Replies are listed 'Best First'.
Re^3: Time to seconds
by tadman (Prior) on Nov 16, 2001 at 00:31 UTC
    This is true to some extent, but in this case, I wanted to make sure that the entries were processed in the proper order, being from highest to lowest. That they happen to sort both numerically and alphabetically is indeed curious, however the addition of 'y' for years would throw that out of whack, and is a style of programming best reserved for Golf.

    The behaviour of 'keys %time_value' is not always in the order they were added, at least under some historical versions of Perl. Best to avoid making assumptions, I suppose. As much as I don't like maintaining inter-related structures, such as these, I didn't want to make a sort_by_value routine even more.
      Actually, it is not just "some historical versions" of Perl: it is one of the most important properties of hashes that the order of pairs they hold is (for all intents and purposes) random. Most importantly, adding a single pair to a hash may lead to getting the pairs back in an entirely different order. This order is of course not actually random: it's deterministic if you know the hash lookup function. That however may change between different versions and ports of Perl; if nothing else, then this alone means scripts have no business assuming anything about it.
        I saw a sorted hash pm somewhere, either in the examples for tie or maybe in Conway's book.
      Hmm, I thought your code was idempotent: it would find the parts in any location of the string. So it should swollow the parts in the wrong order, or you can try the parts in any order. You delete out of the string each one you find, so anything left is stuff you didn't recognise and that causes an error, when you're done with everything you do know.

      If it's not, get rid of the ^ and give it a spin.

      —John

      P.S. it's the to_string you want the correct order for, right? That wasn't part of the original problem, but that's not a problem:

      @value_sorted_keys= sort { $x{a} <=> $x{b} } (keys %x);
        It is true that it would find them in any order, but that if there were duplicates, it would generate an error. I wasn't sure if there might be some circumstance where '3s2m' might be valid input. Hey, you never know!

        You need the correct order for the encoding only, yes, not the decoding. The only reason I made that function was for the sake of completeness, and to validate that my decodes were correct using the test harness.
        A definition of idempotent for the curious.