Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

perl hash

Options
  • 13-06-2008 10:06am
    #1
    Registered Users Posts: 26,579 ✭✭✭✭


    i have a hash that is indexed by a datetime eg. 2008-06-11 15:29:57 and it's value is a url.
    e.g. $urls{2008-06-11 15:29:57} = report_2008-06-11 15:29:57.html

    want i want to do is to sort this hash by it's key and then reverse it so that the latest date is at the begining of the hash.
    e.g.

    if the hash is sorted like so:
    $urls{2008-06-06 16:07:28} = report_2008-06-06 16:07:28.html
    $urls{2008-06-07 20:30:20} = report_2008-06-07 20:30:20.html
    $urls{2008-06-11 15:29:57} = report_2008-06-11 15:29:57.html

    i want this:
    $urls{2008-06-11 15:29:57} = report_2008-06-11 15:29:57.html
    $urls{2008-06-07 20:30:20} = report_2008-06-07 20:30:20.html
    $urls{2008-06-06 16:07:28} = report_2008-06-06 16:07:28.html

    i can achieve this sorting easily by doing this:
    foreach my $key (sort keys %urls)
    {
        print $key :: $urls{$key};
    }
    
    how would i go about reversing this? i tried this which works on arrays:

    %urls = reverse %urls;

    but that just reverse the keys, making the actual value be the key and the actual key be the value.

    anyone any ideas?


Comments

  • Registered Users Posts: 5,112 ✭✭✭Blowfish


    Perl uses $a and $b as special variables, which you can use as arguments to sort.

    It's been a while since I've used it, but I think this will do it:

    %sorted_urls = sort {lc $b cmp lc $a} keys %urls;


  • Closed Accounts Posts: 286 ✭✭Kev


    foreach my $key (reverse sort keys %urls)
    {
    print "$key :: $urls{$key}";
    }


  • Registered Users Posts: 6,509 ✭✭✭daymobrew


    Expanding on Blowfish's idea, you could have your sort function convert the date/time into 'seconds since epoch' e.g. use Time::Local (after splitting the string into the appropriate components).

    Or, do this Time::Local conversion, making the returned number your hash key. Then sorting is easy. And the number is easily converted back to a string with strftime.


  • Closed Accounts Posts: 1,444 ✭✭✭Cantab.


    Here's a bookmark from my del.ico.us]

    I'm always referencing this when I get mixed up with hash sorts.

    http://www.rocketaware.com/perl/perlfunc/sort.htm


Advertisement