home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomePerl CookbookSearch this book

5.14. Finding the Most Common Anything

Problem

You have an aggregate data structure, such as an array or a hash. You want to know how often each element in the array (or key or value in the hash) occurs. For instance, if your array contains web server transactions, you might want to find the most commonly requested file. If your hash maps usernames to number of logins, you want to find the most common number of logins.

Solution

Use a hash to count how many times each element, key, or value appears:

%count = ();
foreach $element (@ARRAY) {
    $count{$element}++;
}

Discussion

Any time you want to count how often different things appear, you should probably be using a hash. The foreach adds one to $count{$element} for every occurrence of $element .


Previous: 5.13. Presizing a Hash Perl Cookbook Next: 5.15. Representing Relationships Between Data
5.13. Presizing a Hash Book Index 5.15. Representing Relationships Between Data

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru