如何编写从另一个文件读取的 Perl 脚本? [英] How can I write a Perl script that reads from another file?

查看:45
本文介绍了如何编写从另一个文件读取的 Perl 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 Perl 脚本来读取带有数字列的 file.txt,

I want to write a Perl Script that reads a file.txt with columns of numbers,

20  30  12
31  20  54
63  30  21
11  12  10

并进行一些计算,例如平均值.我不知道如何声明和初始化它.我有这个例子,它正在寻找中位数,并且它已经声明了数据,在我的例子中,数据在一个文件中,而不是在脚本中,并且想要计算中位数.有吗..#!/usr/bin/perl

and do some calculations, for example the mean. I don't know how to declare and initialize it. I've got this example, in which is looking for the median, and it has the data declared, in my case, the data is in a file, not in the script and want to calculate the median. there is it.. #!/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;

推荐答案

这个 shell 单行将第一个列乘以第二个列:

This shell one-liner multiply first col with second one :

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

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

And the perl script version with your new requirements and the file with 3 cols :

#!/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";
}

你可能会明白发生了什么,而不仅仅是剪切 &粘贴;)

You may understand what's going on instead of just cut & paste ;)

运行脚本:

./script.pl file_with_cols.txt

这篇关于如何编写从另一个文件读取的 Perl 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆