I am not sure I understand what you require, but if it is "How might I sort the keys or values of a hash by the index in the
@cols array of the value of the hash element", then it is necessary to first make a mapping of the elements of the
@cols array to their indices: another hash.
Once you have the element-to-index mapping of the array, it is straightforward to sort the keys or values of the original hash by these indices.
>perl -wMstrict -le
"my @cols = qw(bar wobble mosh hop);
my %hash = (
wibble => $cols[1],
foo => $cols[0],
hip => $cols[3],
mish => $cols[2],
);
my %i_map = map { $cols[$_] => $_ } 0 .. $#cols;
print
join ' ',
qq{keys sorted by \@cols index of value: \n},
sort { $i_map{ $hash{$a} } <=> $i_map{ $hash{$b} } }
keys %hash
;
print
join ' ',
qq{values sorted by \@cols index of value: \n},
sort { $i_map{$a} <=> $i_map{$b} }
values %hash
;
"
keys sorted by @cols index of value:
foo wibble mish hip
values sorted by @cols index of value:
bar wobble mosh hop
The preceding assumes that every value of the hash is an element of the array; it would be wise to validate this assumption.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.