Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Array Question

by Roger (Parson)
on Aug 19, 2005 at 14:33 UTC ( #485159=note: print w/replies, xml ) Need Help??


in reply to Array Question

There are two problems here:
1) count the occurance of words
2) display the words and occurances in decending order.

Try this...
my %count; for (@letters) { $count{$_}++; } for ( map { $_->[0] } sort { $b->[1] <=> $a->[1] } map { [ $_, $count{$_} ] } keys %count ) { print $_, "=>", $count{$_}, "\n"; }


Replies are listed 'Best First'.
Re^2: Array Question
by ikegami (Patriarch) on Aug 19, 2005 at 14:44 UTC

    Using Schwartzian Transform here is overkill, because hash lookups are very efficient. Simplification:

    my @letters = qw( red red red blue white yellow blue navy navy green white cars ); my %count; $count{$_}++ foreach @letters; print("$_ => $count{$_}\n") foreach sort { $count{$b} <=> $count{$a} } keys %count;

    Output:

    red => 3 blue => 2 white => 2 navy => 2 cars => 1 green => 1 yellow => 1

    Kudos for being the first to sort the results, though.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2022-12-10 05:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?