好的,所以我对 Perl 很陌生。我有一个文本文件,文件中有 4 列数据(日期、时间、文件大小、文件)。我需要创建一个可以打开文件并获取文件平均大小的小脚本。我在网上阅读了很多,但我仍然不知道如何去做。到目前为止,这就是我所拥有的,但我不确定我是否接近正确地做到这一点。
#!/usr/bin/perl
open FILE, "files.txt";
#@array = File;
while(FILE){
#chomp;
($date, $time, $numbers, $type) = split(/ /,<FILE>);
$total += $numbers;
}
print"the total is $total\n";
这就是数据在文件中的外观。这些只是其中的一小部分。我需要获取第三列中的数字。
12/02/2002 12:16 AM 86016 a2p.exe
10/10/2004 11:33 AM 393 avgfsznew.pl
11/01/2003 04:42 PM 38124 c2ph.bat
最佳答案
你的程序相当接近工作。通过这些更改,它将完全按照您的意愿行事
use strict
和 use warnings
在程序开始时,使用 my
声明所有变量.这将帮助您找到许多您可能会忽略的简单错误 open
的三参数形式,并始终检查任何 open
的返回状态调用$total
循环外的变量。在循环中声明它意味着每次循环都会创建和销毁它,并且它不能累积总数 $count
以同样的方式变量。您将需要它来计算平均值 while (FILE) {...}
只是测试 FILE
是真的。你需要读取它,所以你必须使用 readline
运算符(operator)喜欢 <FILE>
split
(不带任何参数)将返回 $_
中的所有非空格字段作为列表 AM
或 PM
每行中的字段 这是对您的代码的修改,可以正常工作
use strict;
use warnings;
open my $fh, '<', "files.txt" or die $!;
my $total = 0;
my $count = 0;
while (<$fh>) {
my ($date, $time, $ampm, $numbers, $type) = split;
$total += $numbers;
$count += 1;
}
print "The total is $total\n";
print "The count is $count\n";
print "The average is ", $total / $count, "\n";
输出
The total is 124533
The count is 3
The average is 41511
关于perl - 使用 Perl 对文本文件中的一列数字求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187239/