Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count duplicates in an array or file!

Status
Not open for further replies.

youthman

Programmer
Apr 28, 2004
49
US
Hello guru's!
I have a comma seperated file that contains nothing but numbers. All I need to know is the number of times that each number occures in the file. Is there a way to read a file and just pull out the number of times each number is listed, or do this in an array? The numbers are NOT sequential and there will not be all numbers listed. In other words, a single file may look like:
1,5,1,4,2,11,23,10000,2,3945,4,99,61
and another file may look like:
8,33,22,4

What I need to know is that in file #1, the Number 1 appears 2 times, the number 5 appears 1 time, 4 appears 1 time, 2 appears 2 times, etc. . .

There are a possible 10,000 numbers, so doing a series of if statements on the file is out of the question!

Any help? Thanks! :)
 
I would push the numbers within each line into a hash, using the number as the key and then increment the value by one each time you write to it.

Code:
$hash{$number}++;

- Rieekan
 
Thanks for the fast reply! I know NOTHING about hashes! (I am VERY NEW!) How do I go about putting them into hashes, and how do I go about getting the totals back out?
 
Code:
#!perl
use strict;
use warnings;

my %h;
while (<DATA>) {
    chomp;
    $h{$_}++ for split /\s*,\s*/;
}
print "Number\tCount\n";
for (sort {$a<=>$b} keys %h) {
    printf "%6d\t%5d\n", $_, $h{$_};
}

__DATA__
1,5,1,4,2,11,23,10000,2,3945,4,99,61 
8,33,22,4
1,5,1,4,2,11,23,10000,2,3945,4,99,61 
8,33,22,4
Output:
Code:
Number	Count
     1	    4
     2	    4
     4	    6
     5	    2
     8	    2
    11	    2
    22	    2
    23	    2
    33	    2
    61	    2
    99	    2
  3945	    2
 10000	    2
If you know as little about Perl as you say, you should read a book. Go to and look for books. I recommend Learning Perl for starters.

HTH
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top