bk1388 has asked for the wisdom of the Perl Monks concerning the following question:
hi monks I have a file with several hundred thousand numbers , and I need to determine the number of times each value is present in the file and print out a numeric sorted list of values and the number of times seen. I thought using a hash such a the example below would work . my idea was For each number in the array, if the number already exists in the hash, then increment the value by 1 ; else if it does not exist in the hash, then add the number to the hash with the initial value of 1 . HOWEVER IT'S NOT WORKING :( AND I CAN'T FIND WHY, PLEASE HELP
my @numbers = (1..100) my %count; foreach $number(@numbers) { if (exists $count{$number}) { $count{$number}++; } else { $count{$number} = 1; } } foreach (sort keys %count) { print "$number occurs $count{$number} time(s)\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: counting elements using a hash
by roboticus (Chancellor) on Sep 23, 2012 at 01:42 UTC | |
|
Re: counting elements using a hash
by davido (Cardinal) on Sep 23, 2012 at 06:36 UTC | |
|
Re: counting elements using a hash
by CountZero (Bishop) on Sep 23, 2012 at 07:12 UTC | |
|
Re: counting elements using a hash
by Marshall (Canon) on Sep 23, 2012 at 02:02 UTC | |
by AnomalousMonk (Archbishop) on Sep 23, 2012 at 09:08 UTC | |
by Marshall (Canon) on Sep 23, 2012 at 12:28 UTC | |
by bk1388 (Initiate) on Sep 23, 2012 at 21:13 UTC | |
|
Re: counting elements using a hash
by Kenosis (Priest) on Sep 23, 2012 at 06:58 UTC | |
by Anonymous Monk on Sep 23, 2012 at 07:01 UTC | |
by Kenosis (Priest) on Sep 23, 2012 at 07:05 UTC |