in reply to Turning a hash into a line of links
Personally, I tend to use map< for "making a new X for every y in the array", i.e. when I want to create a different list of N items, as is the case here. If I want a side-effect (e.g. printing, or calling a function to process every y in the array) I tend to write the explicit loop for clarity. map has that 'pipeline' feel to it.
You mentioned having a leading space on one of the keys, in order to force the sort order.
This is ingenious, but leaves a space in your output and doesn't scale easily to giving your greater control over the sort order. If you want to do that, one way to extend your idea would be to add a prefix, say A_, B_, etc, to each key, in the order you want them displayed.
You can then include the prefix stripping as part of your processing, which brings us to map's close relative (evil twin?) apply. This is almost identical to map, but works on a copy of the items from the array, so it appropriate when you want to change the value of $_ in the processing step (as we do here, to strip off the sorting tag at the front):
Note that you need to pull in apply from List::MoreUtils, where you'll also find lots of other goodies in a similar vein, allowing you to replace loops with simpler, hopefully clearer, code.#!perl -w use strict; use List::MoreUtils qw/apply/; my %sections=( A_DMA => 'dma', B_FST => 'dma/fst', C_MRA => 'dma/mra', D_BKS => 'bks', E_MSU => 'dma/msu', F_FMA => 'dma/fma', G_FOMC => 'dma/FOMC', ); print join("\n", apply { s/^\w_//; } sort keys %sections);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Turning a hash into a line of links
by johngg (Canon) on Dec 13, 2006 at 10:19 UTC | |
by jbert (Priest) on Dec 13, 2006 at 10:40 UTC | |
by johngg (Canon) on Dec 13, 2006 at 11:36 UTC |