这个Perl文件的目的是处理一个名为"测量"的文件,压缩数据并计算最后三列的平均值。
-bash-3.2$ cat measurements
F gge0001x gge0001y gge0001z
D 12-30-2006 12-30-2006 12-30-2006
T 14:15:20 14:15:55 14:16:27
S a69 a69 a69
B 15.8 16.1 15
M gge06001 gge06001 gge06001
P 30.1 29.6 29.9
Q 20.2 22.3 23.4
R 1006.2 1003.5 999.8
U 1011.8 1011.8 1005
X 34.7 35.2 35.1
A 38.994 38.994 38.994
G 107.71 107.71 107.71
H 8.395 8.406 8.368
O 37.141 36.823 36.621
C 7.55 7.532 7.437
K 28.193 27.902 27.856
W 212.86 210.15 207.15
L 68.3 67.9 67.6
我想知道如何做是在三列上执行所述平均计算的最佳实践(我应该编写一个单独的流程,还是在第一个流程中将其合并)?也许在第一个过程中,它是否可以说(对于数组索引1-3,添加array [1] array [2] array [3])?如何只用结果覆盖文件?
#! /usr/bin/perl
# Declare strict, constant.
use strict;
use constant {
max_files => 1,
};
# Gather second column for data information, append to "file.prc".
sub process_file {
my ($file) = @_;
open(FILEIN, $file) || die ("Cannot open $file.");
open(FILEOUT, ">$file.prc");
while (<FILEIN>) {
# Ensure UNIX file endings & condense whitespace.
s/\r\n?/\n/g;
s/ +/ /g;
# If the line begins with DBPQRHOCKWL, print the relating columns into separate indexes.
if (/^[DBPQRHOCKWL]/) {
chomp(my @line = split(/ /));
print(FILEOUT "$line[1]\n");
print(FILEOUT "$line[2]\n");
print(FILEOUT "$line[3]\n");
}
}
close(FILEIN);
close(FILEOUT);
}
# Gather first column for header information, append to "header.prc".
open(FILEIN, "measurements") || die ("Cannot open the measurements file.");
open(FILEOUT, ">header.prc");
while (<FILEIN>) {
# Ensure UNIX file endings & condense whitespace.
s/\r\n?/\n/g;
s/ +/ /g;
# If the line begins with DBPQRHOCKWL, print that first column.
if (/^[DBPQRHOCKWL]/) {
chomp(my @line = split(/ /));
print(FILEOUT "$line[0]\n");
}
}
close(FILEIN);
close(FILEOUT);
# Process the actual measurements file.
&process_file("measurements");
open(F1, "header.prc") || die ("Cannot open header.prc.");
open(F2, "measurements.prc") || die ("Cannot open measurements.prc.");
open(FILEOUT, ">lab6.prc");
# Combine the header with the measurement data.
while (<F1>) {
chomp(my $col1 = $_);
chomp(my $col2 = <F2>);
print(FILEOUT "$col1 $col2\n");
}
close(F1);
close(F2);
close(FILEOUT);
# file cleanup
`rm measurements.prc`;
`rm header.prc`;
最佳实践和方向是我之后的信息。提前谢谢!