使现代化
这是你的代码更新,我认为你想做什么。它写入两个输出文件而不是一个:
pressure.txt
和
avg.txt
. 我还修复了代码中的一些不良实践;特别是你应该
use strict
use warnings 'all'
在每个Perl程序的顶部(我把它们放在这里,因为我不知道程序的顶部是什么样子),您需要在第一个使用点声明所有变量
my
我还从append更改了输出文件的打开模式。我想你不希望每个输出都添加到文件的末尾?
我希望这有帮助
my ( $outputfile, $avg_file ) = qw/ pressure.txt avg.txt /;
open my $out_fh, '>', $outputfile" or die qq{Unable to open "$outputfile" for output: $!};;
open my $avg_fh, '>', $avg_file" or die qq{Unable to open "$avg_file" for output: $!};;
print $out_fh "time [s] location distance [mm] Max Pressure [Pa]\n";
print $avg_fh "Distance [mm] Avg Pressure [Pa]\n";
for ( 0 .. 10 ) {
my $i = $_ * 10; # $i = 0, 10, 20, ... 100
my $location = "x$i";
my $timestep_list = getValue( 'DATA READER', 'Timestep List' );
my @timesteps = split /,\s*/, $timestep_list;
my ($n, $total_maxp) = (0, 0);
for my $ts ( @timesteps ) {
my $time = getValue( 'DATA READER', 'Current Timevalue' );
my $max_pressure = maxVal( 'Pressure', $location );
print $out_fh "$time $location $i $max_pressure\n";
++$n;
$total_maxp += $max_pressure;
}
printf $avg_fh "%-16d%-.3e\n", $i, $total_maxp / $n;
}
close $out_fh or die $!;
close $avg_fh or die $!;
use strict;
use warnings 'all';
use Scalar::Util 'looks_like_number';
use List::Util 'sum';
my %data;
while ( <DATA> ) {
my ($t, $loc, $dist, $maxp) = split;
next unless looks_like_number($maxp);
push @{ $data{$dist} }, $maxp;
}
for my $dist ( sort { $a <=> $b } keys %data ) {
my $maxp = $data{$dist};
$maxp = sum(@$maxp) / @$maxp;
printf "%-16d%-.3E\n", $dist, $maxp;
}
__DATA__
time [s] location distance [mm] Max Pressure [Pa]
1 x0 0 3.531e5
2 x0 0 7.795e5
3 x0 0 5.265e5
.. .. .. ..
.. .. .. ..
10 x0 0 ..e5
1 x10 10 4.267e5
2 x10 10 9.987e5
3 x10 10 1.443e5
.. .. .. ..
.. .. .. ..
10 x10 10 ..e5
输出
0 5.530E+005
10 5.232E+005