So, your issue is that you have a number preceded by alphabetic characters, and you want to do numeric sorting on the numbers? In your sample, all your keys begin with
hs. Is this guaranteed? Also, what is this
%planets hash? Essentially, if you want to sort based on a substring of your key, then you will need to parse out that substring.
The easiest answer here would probably be to keep leading 0's on your keys, e.g. hs01 instead of hs1. Barring that, you could do the parsing in a named sub:
use strict;
my %planets;
my %cuantas_veces_sale;
for my $nombre (sort keysort keys %cuantas_veces_sale) {
print "$nombre\n";
};
sub keysort {
return $planets{$a} <=> $planets{$b} if $planets{$a} <=> $planets{
+$b};
my ($num_a) = $a =~ /(\d+)/;
my ($num_b) = $b =~ /(\d+)/;
$num_a <=> $num_b;
}
or possibly cache the parse in a hash ahead of time:
use strict;
my %planets;
my %cuantas_veces_sale;
my %alphas = map {$_ => /(\D+)/} keys %cuantas_veces_sale;
my %numerics = map {$_ => /(\d+)/} keys %cuantas_veces_sale;
for my $nombre (sort { $planets{$a} <=> $planets{$b}
or $alphas{$a} cmp $alphas{$b}
or $numerics{$a} cmp $numerics{$b} } keys %cuant
+as_veces_sale) {
print "$nombre\n";
};
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
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.