可能重复:
How can I write a Perl script that reads from another file?
我想写一个Perl脚本,它读取带有数字列的文件.txt
20 30 12
31 20 54
63 30 21
11 12 10
并做一些计算,例如均值,中位数等。我不知道如何声明和初始化它。
我有这个例子,正在寻找中位数。它具有在文件中声明的数据,而不是在脚本中,我想计算中值。
#!/usr/bin/perl
#data points
@vals = ( 33, 23, 55, 39, 41, 46, 38, 52, 34, 29, 27, 51, 33, 28 );
print "UNSORTED: @vals\n";
#sort data points
@vals = sort(@vals);
print "SORTED: @vals\n"; #test to see if there are an even number of data points
if( @vals % 2 == 0) {
#if even then:
$sum = $vals[(@vals/2)-1] + $vals[(@vals/2)];
$med = $sum/2;
print "The median value is $med\n";
}
else{
#if odd then:
print "The median value is $vals[@vals/2]\n";
}
exit;
感谢您的任何建议。 ;)