in reply to counting elements using a hash

Consider the following option:

use strict; use warnings; use Regexp::Common; my %numbers; open my $fh, '<', 'numbersFile.txt' or die $!; while (<$fh>) { $numbers{$1}++ while /($RE{num}{real})/g; } close $fh; print "Number: $_\tCount: $numbers{$_}\n" for sort { $a <=> $b } keys %numbers;

Contents of numbersFile.txt:

12.7 abce -3.14 21 This is a line with 8 words in it. 10000 is a big number. Looks like 21 and 12.7 again. 5 + 7 = 12

Output:

Number: -3.14 Count: 1 Number: 5 Count: 1 Number: 7 Count: 1 Number: 8 Count: 1 Number: 12 Count: 1 Number: 12.7 Count: 2 Number: 21 Count: 2 Number: 10000 Count: 1

Regexp::Common is used (the $RE{num}{real} in the regex) to capture the numbers on each line that's read. You may not need to use it, if the numbers are just sets of decimals integers, in which case \d+ can be used, instead.

The while before the regex insures processing all numbers on a line. The anonymous subroutine { $a <=> $b } is used to sort numbers.

Hope this helps!

Replies are listed 'Best First'.
Re^2: counting elements using a hash
by Anonymous Monk on Sep 23, 2012 at 07:01 UTC

    if the numbers are just sets of decimals, in which case \d+ can be used

    I call those integers, I think of decimals as reals (0.0)

      Oh, my! They are called integers. Thank you for bringing this to my attention. Will correct. Time for sleep...