Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Array Question

by Anonymous Monk
on Aug 19, 2005 at 14:25 UTC ( [id://485151]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a simple question but it's confusing me. I have an array with multiple names and some of them are the same. I need to count how many instances of each letter are in this array, can some one give a little help here? Results should be like:
red=3
blue=2
white=2
yellow=1
...
Thanks for the help!
#! /perl/bin/perl use strict; my @letters = ("red","red","red","blue","white","yellow","blue","navy" +,"navy","green","white","cars"); foreach my $i (sort(@letters)) { print "$i\n"; }

Replies are listed 'Best First'.
Re: Array Question
by Roy Johnson (Monsignor) on Aug 19, 2005 at 14:30 UTC
    Count using a hash:
    my %count; ++$count{$_} for @letters;

    Caution: Contents may have been coded under pressure.
Re: Array Question
by Transient (Hermit) on Aug 19, 2005 at 14:30 UTC
    There are many examples already in the monastery, but here's one way:
    #! /perl/bin/perl use Data::Dumper; use strict; my @letters = ("red","red","red","blue","white","yellow","blue","navy" +,"navy","green","white","cars"); my %count = (); $count{$_}++ for @letters; print Dumper( \%count );
Re: Array Question
by Roger (Parson) on Aug 19, 2005 at 14:33 UTC
    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"; }


      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: perlquestion [id://485151]
Approved by Tanalis
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-19 21:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found