如何编写从另一个文件读取的Perl脚本?

时间:2011-11-23 03:58:43

标签: perl statistics

我想写一个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;

3 个答案:

答案 0 :(得分:2)

使用open命令。该页面上有很多很好的例子。

答案 1 :(得分:1)

这个shell单行乘以第一个col与第二个:

perl -lane 'print $F[0] * $F[1]' <FILE>

编辑:以及带有新要求的perl脚本版本和带有3列的文件:

#!/usr/bin/perl

use strict;
use warnings;

my (@vals, $sum, $med);

while (<>) {
    @vals = split;

    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";
    } 

    print "\n";
}

你可能会理解发生了什么,而不仅仅是切割和切割。粘贴;)

运行脚本:

./script.pl file_with_cols.txt

答案 2 :(得分:1)

以下是建议使用的功能(参见function reference):

  1. 打开文件进行阅读:使用open功能
  2. 遍历每一行:while (my $line = <$filehandle>)
  3. 删除尾随换行符:使用chomp
  4. 从每一行中提取值:使用split函数
  5. 将值存储在数组中:使用push
  6. 要验证您的阵列最终是否具有您想要的内容:

    use Data::Dumper;
    print Dumper \@vals;
    

    更新

    在没有给出完整答案的情况下(因为这是家庭作业),请查看函数参考的每个条目中的示例代码。

    这是让你入门的东西:

    open my $filehandle, '<', $filename
        or die "Couldn't open $filename";
    while (my $line = <$filehandle>) {
        # do stuff with $line
    }
    close $filehandle;