如何编写从另一个文件读取的 Perl 脚本?
我想编写一个 Perl 脚本来读取包含数字列的 file.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;
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
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 open 命令。该页面上有很多很好的例子。
Use the open command. Plenty of good examples on that page.
这个shell单行将第一列与第二列相乘:
编辑:以及具有您的新要求的perl脚本版本和具有3列的文件:
您可能会明白发生了什么,而不仅仅是剪切和删除。粘贴;)
运行脚本:
This shell one-liner multiply first col with second one :
EDIT: And the perl script version with your new requirements and the file with 3 cols :
You may understand what's going on instead of just cut & paste ;)
To run the script :
以下是建议使用的函数(请参阅函数参考):
open
函数while (my $line = <$filehandle>)
chomp
split
函数push
要验证您的数组最后是否具有您想要的内容:
更新
没有给您完整的答案(因为这是家庭作业)查看函数参考的每个条目中的示例代码。
这里有一些可以帮助您开始的东西:
Here are suggested functions to use (see the function reference):
open
functionwhile (my $line = <$filehandle>)
chomp
split
functionpush
To verify that your array has what you want at the end:
UPDATE
Without giving you the entire answer (since this is homework) have a look at the sample code in each entry of the function reference.
Here's something to get you started: