G'day coding1227,
Welcome to the monastery.
First off, I need to say that this looks like an XY Problem. You've decided upon a solution, presented test data that fits that solution and asked how to code the solution. What you haven't done is fully explained the problem; in particular, you haven't said why you've chosen "the previous 3 lines" and what's special about the first three lines that guarantees that they will always contain "good" data values.
If there's simply an omission in your post, and the solution is valid, then this logic does what you want:
#!/usr/bin/env perl use strict; use warnings; use List::Util 'sum'; my $allowable_drift = 0.5; my @test_data; while (<DATA>) { my $test_field = (split)[3]; if (@test_data < 3) { print; push @test_data, $test_field; next; } my $avg = sum(@test_data) / 3; if (abs($avg - $test_field) <= $allowable_drift) { print; shift @test_data; push @test_data, $test_field; } else { print "Outlier: $_"; } } __DATA__ A15 26.62 765 27.30 4.3 A11 26.63 763 27.28 4.2 A12 26.68 767 27.29 4.3 A16 26.64 768 27.30 4.2 A11 26.62 761 27.31 4.1 A15 26.62 765 27.30 4.3 A15 26.63 763 27.28 4.2 A16 26.68 767 2.29 4.3 A17 26.64 768 27.30 4.2 A18 26.62 761 27.31 4.1
Output:
A15 26.62 765 27.30 4.3 A11 26.63 763 27.28 4.2 A12 26.68 767 27.29 4.3 A16 26.64 768 27.30 4.2 A11 26.62 761 27.31 4.1 A15 26.62 765 27.30 4.3 A15 26.63 763 27.28 4.2 Outlier: A16 26.68 767 2.29 4.3 A17 26.64 768 27.30 4.2 A18 26.62 761 27.31 4.1
However, with this data (record 8 moved to record 2):
__DATA__ A15 26.62 765 27.30 4.3 A16 26.68 767 2.29 4.3 A11 26.63 763 27.28 4.2 A12 26.68 767 27.29 4.3 A16 26.64 768 27.30 4.2 A11 26.62 761 27.31 4.1 A15 26.62 765 27.30 4.3 A15 26.63 763 27.28 4.2 A17 26.64 768 27.30 4.2 A18 26.62 761 27.31 4.1
You get this output:
A15 26.62 765 27.30 4.3 A16 26.68 767 2.29 4.3 A11 26.63 763 27.28 4.2 Outlier: A12 26.68 767 27.29 4.3 Outlier: A16 26.64 768 27.30 4.2 Outlier: A11 26.62 761 27.31 4.1 Outlier: A15 26.62 765 27.30 4.3 Outlier: A15 26.63 763 27.28 4.2 Outlier: A17 26.64 768 27.30 4.2 Outlier: A18 26.62 761 27.31 4.1
I'll leave you to provide an update on the problem if that's appropriate. :-)
-- Ken
In reply to Re: comparing numbers from previous lines in a file?
by kcott
in thread comparing numbers from previous lines in a file?
by coding1227
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |