in reply to Re: Turning a hash into a line of links
in thread Turning a hash into a line of links

I think that mangling the keys by adding a prefix could quickly get out of hand and become difficult to manage, with strategies required if the number of sections goes over 26 etc. If you have one particular key, as in the OP, that has to come first then sort on whether you have found that key before the lexical sort, like this

#!/usr/local/bin/perl -l # use strict; use warnings; my %sections = ( DMA => q{dma}, FST => q{dma/fst}, MRA => q{dma/mra}, BKS => q{bks}, MSU => q{dma/msu}, FMA => q{dma/fma}, FOMC => q{dma/FOMC}); my $thisKeyFirst = q{DMA}; my @sortedKeys = map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[0] cmp $b->[0] } map { [$_, $_ eq $thisKeyFirst] } keys %sections; print for @sortedKeys;

which produces

DMA BKS FMA FOMC FST MRA MSU

It seems to me that it would be easier to manage that way. It you had a few special keys that fell into this category this method would still work but with a hash to hold the order of the specials, highest value first and keys not in specials hash getting zero. Something like (not tested)

my %specials = ( DMA => 2, MSU => 1); ... map { [$_, exists $specials{$_} ? $specials{$_} : 0] } keys %sections;

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^3: Turning a hash into a line of links
by jbert (Priest) on Dec 13, 2006 at 10:40 UTC
    I think at that point, it would be better to just maintain a real order, via a list, and associating values as part of an array ref.
    my @sections = ( [DMA => 'dma'], [FST => 'dma/fst'], [MRA => 'dma/mra'], [BKS => 'bks'], [MSU => 'dma/msu'], [FMA => 'dma/fma'], [FOMC => 'dma/FOMC'], ); my @la = map { a( {-href => "/$_->[1]"}, "$_->[0] HOME" ) } @sections; print join "\n|", @la;
    In fact that's probably better than the key-mangling for this number of keys too.
      The problem with that is you lose the ability to do look-ups so you have to iterate over the array to find the 'FMA' key/value pair. You could keep the hash but make it a HoH with the sort order held inside, like

      my %sections = ( DMA = {attrib => q{dma}, sortOrder => 1}; ...

      but that strikes me as more complicated when most keys don't need it, just those with an odd ordering requirement.

      Cheers,

      JohnGG