Perl:读取数组并计算相应的百分位数



我正在尝试编写一个perl代码,该代码读取具有一系列数字的文本文件,计算并打印出与百分位数对应的数字。我无法访问其他统计模块,所以我想坚持使用纯perl编码。提前感谢!

输入文本文件如下:

197
98
251
82
51
272
154
167
38
280
157
212
188
88
40
229
228
125
292
235
67
70
127
26
279
.... (and so on)

我的代码是:

#!/usr/bin/perl
use strict;
use warnings;
my @data;
open (my $fh, "<", "testing2.txt")
                         or die "Cannot open: $!n";
while (<$fh>){
    push @data, $_;
}
close $fh;
my %count;
foreach my $datum (@data) {
    ++$count{$datum};
}
my %percentile;
my $total = 0;
foreach my $datum (sort { $a <=> $b } keys %count) {
    $total += $count{$datum};
    $percentile{$datum} = $total / @data;
    # percentile subject to change
    if ($percentile{$datum} <= 0.10) {   
        print "$datum : $percentile{$datum}nn";
    }
}

期望输出:

2 : 0.01
3 : 0.01333
4 : 0.01666
6 : 0.02
8 : 0.03
10 : 0.037
12 : 0.04
14 : 0.05
15 : 0.05333
16 : 0.06
18 : 0.06333
21 : 0.07333
22 : 0.08
25 : 0.09
26 : 0.09666

其中格式为#number from the list: #对应的百分位数

要在@data中存储不带换行符的数字,只需在推入之前添加chomp;,或在读取完它们之后添加chomp @data;

如果您的输入文件有MSWin样式的换行符,使用dos2unixfromdos将其转换为*nix样式。

另外,试着学习如何缩进你的代码,它可以提高可读性。并考虑将$total重命名为$running_total,因为您使用的值随着它的变化。

最新更新