LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Perl to compare value differences (http://www.linuxquestions.org/questions/programming-9/perl-to-compare-value-differences-4175444416/)

eminempark 01-06-2013 08:13 PM

Perl to compare value differences
 
For example, I have a data in "one.txt" which is
Code:

# ID Temperature
1 25.0
2 25.0
3 25.1
4 25.6
5 25.7
6 25.9

And I want to filter out the temperature which has difference less than 0.2 with previous REGISTERED value. The output should be
Code:

# ID Temperature
1 25.0
4 25.6
6 25.9

The mechanism works like this
ID 1, diff |25.0 - 0| = 25.0 (ID 1 register)
ID 2, diff |25.0 - 25.0 (TEMP. FROM ID 1)| = 0 (ID 2 filter out)
ID 3, diff |25.1 - 25.0 (TEMP. FROM ID 1)| = 0.1 (ID 3 filter out)
ID 4, diff |25.6 - 25.0 (TEMP. FROM ID 1)| = 0.6 (ID 4 register)
ID 5, diff |25.7 - 25.6 (TEMP. FROM ID 4)| = 0.1 (ID 5 filter out)
ID 6, diff |25.9 - 25.6 (TEMP. FROM ID 4)| = 0.3 (ID 6 register)
Any idea?

binary_pearl 01-06-2013 09:20 PM

Not sure how familiar you are with perl, but this framework below may help. What it's doing is to open the file one.txt, and then read the contents into an array (@records). If then loops through each line, using a regular expression to break apart the id, the integear part of the temperature and the decimal part of the temperature. From there you can use those variables ($id, $int, $decimal) for further math. Hope this helps:

Code:

#!/usr/bin/perl

use strict;

my @records = ();
my $record = "";

my $id = "";
my $int = "";
my $decimal = "";

open (INPUTFILE, "one.txt");

@records = <INPUTFILE>;

foreach $record (@records) {
        chomp $record;

        if ($record =~ m/([0-9].*)( )([0-9].*)(.)([0-9].*)/) {
                $id = $1;
                $int = $3;
                $decimal = $5;

                #... do stuff
        }
}

close (INPUTFILE);

--Shaun


All times are GMT -5. The time now is 08:45 PM.