以下是我试图处理的输入文件中的几行典型行:
ICC2_DPD 2.7V ma 0.006 0.006 0.006 ... ...
DPD_Rel 2.7V ma 0.062 0.054 0.040 0.065 0.037 0.066 0.071 0.073 ... ... ...
(花车的数量可能会有所不同)以下是我最初的开始:
if(/^(\w+)\s+(\d+\.?\d*)V\s+(\w+)/)
{
print $OUT "$1 $2 $3\n";
}
如果值的数量不同,您将如何捕获浮点值并将其存储到数组/散列中。我坚持如何管理阵列的终止。
答案 0 :(得分:4)
嗯,在你的情况下,我可能会考虑使用split
,分隔空格上的字段:
while (<DATA>) {
my @vals = split; # default split is fine
print join(" ", @vals[3 .. $#vals]), "\n";
}
或者如果您想存储它们,只需将它们推送到数组,或使用带有合适密钥的哈希。有点像...
push @array, [ @vals[3 .. $#vals] ]; # push an array ref
$hash{$vals[0]} = [ @vals[3 .. $#vals] ]; # use a hash
[ ... ]
部分正在创建一个匿名数组引用,然后可以将该行的值存储在单个标量槽中。
答案 1 :(得分:0)
我可能倾向于这样写:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw( sum );
my @data;
while (my $line = <DATA>) {
my ($state, $voltage, $current_unit, $obs) = split ' ', $line, 4;
my @obs = ($obs =~ / ( [0-9] [.] [0-9]+ )/gx);
push @data, {
state => $state,
voltage => $voltage,
current_unit => $current_unit,
obs => \@obs,
average_current => sum(@obs) / @obs,
};
}
for my $x (@data) {
printf(
"State = %-16sAverage current = %.3f%s\n",
@$x{qw(state average_current current_unit)},
);
}
__DATA__
ICC2_DPD 2.7V ma 0.006 0.006 0.006
DPD_Rel 2.7V ma 0.062 0.054 0.040 0.065 0.037 0.066 0.071 0.073
输出:
State = ICC2_DPD Average current = 0.006ma State = DPD_Rel Average current = 0.059ma