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

HI everyone, I want to count the number of occurence of a number in a text. i know how to do it for a character but not for a number. my data contains -
0.000000e+00 105 35324 1.000000e+00 105 35324 2.000000e+00 105 33308 3.000000e+00 105 35324 4.000000e+00 105 33308 5.000000e+00 105 35324 6.000000e+00 105 33227 7.000000e+00 105 33011 8.000000e+00 105 33227 9.000000e+00 105 35606 1.000000e+01 105 33227 1.100000e+01 105 35537

i have to get the number of occurence of the 3rd column.

Thanks

Replies are listed 'Best First'.
Re: to count the number of occurence of a number
by bart (Canon) on Sep 28, 2011 at 10:55 UTC
    You mean the frequency of that value? Use the classic word frequency count idiom (a task that is very simple in Perl: use a hash). It's not because it's a number that you cannot treat it as a string.
    my %frequency; while(<>) { my @column = split ' ' or next; $frequency{$column[2]}++; }
    Now you can just print out what you've got.
    { local($\, $,) = ("\n", "\t"); # tab delimited output foreach (sort { $frequency{$b} <=> $frequency{$a} || $a <=> $b } k +eys %frequency) { print $_, $frequency{$_}; } }
    Here's the result I got from your sample:
    35324 4 33227 3 33308 2 33011 1 35537 1 35606 1
      Hi bart, thanks for ur response, am getting error while compling $frequency requires explicit package.
        It's working fine (Perl v5.10.1):
        #!/usr/bin/perl use strict; use warnings; my %frequency; while(<DATA>) { my @column = split ' ' or next; $frequency{$column[2]}++; } { local($\, $,) = ("\n", "\t"); # tab delimited output foreach (sort { $frequency{$b} <=> $frequency{$a} || $a <=> $b } k +eys %frequency) { print $_, $frequency{$_}; } } __DATA__ 0.000000e+00 105 35324 1.000000e+00 105 35324 2.000000e+00 105 33308 3.000000e+00 105 35324 4.000000e+00 105 33308 5.000000e+00 105 35324 6.000000e+00 105 33227 7.000000e+00 105 33011 8.000000e+00 105 33227 9.000000e+00 105 35606 1.000000e+01 105 33227 1.100000e+01 105 35537

        To get input from a file, see [Re^2: Alphanumeric sort].

        Have a nice day, j