Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: sorting a hash by keys, according to preference

by Tanktalus (Canon)
on Apr 13, 2005 at 03:57 UTC ( #447254=note: print w/replies, xml ) Need Help??

in reply to sorting a hash by keys, according to preference

First off, I'm not sure what order you expect your output to be. I'm going to guess that you want something like this:

.4 .6 .1 .3 .5 .1 .0 .2 .1 .5 .7 .1
In which case, I would create an array with the order of keys you want to go through:
my @keys = qw(start stop step); for my $type (@keys) { print $point->{$type}, "\t"; }
If some of the keys may not appear, you could skip them:
my @keys = qw(start stop step); for my $type (@keys) { next unless exists $point->{$type}; print $point->{$type}, "\t"; }
Or, in the spirit of TMTOWTDI, you could have a hash of weightings:
my %weights = ( start => 10, stop => 20, step => 30 ); for my $type ( sort { $weights{$a} <=> $weights{$b} } keys %$point ) { print $point->{$type}, "\t"; }
But I like the array better. No actual sorting required. The hash weights are more useful when you have great numbers of possible keys to sort, but only a few keys will be in any given hash. In this case, you may not want to generate the weights by hand, but generate them in code:
my %weights = do { my $i = 0; map { $_ => $i++ } qw(start stop step ot +her stuff in order here) };
Hope that helps.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://447254]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2020-12-03 14:39 GMT
Find Nodes?
    Voting Booth?
    How often do you use taint mode?

    Results (56 votes). Check out past polls.