Only inefficiently. If you don't tell Perl to build a hash
lookup, you will have to repeatedly scan the array. But
you can eliminate the Schwartzian sort:
use strict;
use Data::Dumper;
$Data::Dumper::Indent = 1;
my @vals = qw( 1 2 3 1 3 3 3 43 bob 2 bob 6 2 );
my %freqs;
$freqs{$_}++ foreach @vals;
my @sorted = sort {
$freqs{$b} <=> $freqs{$a} or $a cmp $b
} keys %freqs;
print Data::Dumper->Dump([\@sorted], ['*sorted']);
Remember that Schwarzian sorts are good when the sort
step involves a lot of work. Hash lookups are not that
much work. :-)
Incidentally note that way I dump. I had looked that up a
long time ago, but I want to start trying to use that for
brief one-offs. I think it is rather nice to keep my
names intact like that...
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.