frank19 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I am new to perl, so my question can be stupid question. I have file like this: 1 3 5 2 7 6 3 10 7 I want to subtract 2nd column of each line from previous line's 2nd column. I want to have output like this: 1 3 5 2 4 6 3 3 4 Any help will be appreciated.

Replies are listed 'Best First'.
Re: subtracting two lines in file
by almut (Canon) on Jun 19, 2010 at 18:23 UTC

    With proper formatting, your question would've been comprehensible:

    Hi Monks, I am new to perl, so my question can be stupid question. I have file like this:

    1 3 5 2 7 6 3 10 7

    I want to subtract 2nd column of each line from previous line's 2nd column. I want to have output like this:

    1 3 5 2 4 6 3 3 4

    Any help will be appreciated.


    To solve your problem, just store the current value at the end of every iteration, so you still have it in the next iteration:

    #!/usr/bin/perl use strict; use warnings; my $prev_2 = 0; while (<DATA>) { my ($c1, $c2, $c3) = split; printf "%3d %3d %3d\n", $c1, $c2-$prev_2, $c3; $prev_2 = $c2; } __DATA__ 1 3 5 2 7 6 3 10 7

    Output:

    1 3 5 2 4 6 3 3 7

    (BTW, your desired output suggests that you want to subtract the previous value from the current one, not the other way round).

Re: subtracting two lines in file
by toolic (Bishop) on Jun 19, 2010 at 17:04 UTC
    stupid question
    Stupid, no. Poorly formatted, probably. It looks like you only showed one line of your input. Did you really mean to show more than one line? If so, read Writeup Formatting Tips, then update your post, putting your input in code tags.
    I am new to perl
    Read perlintro. That should allow you to attempt to write your own code. Give it a try, and if you still have problems, post the code you tried.
Re: subtracting two lines in file
by JavaFan (Canon) on Jun 20, 2010 at 15:06 UTC
    Is the 4 in your desired output a typo? Or is there another rule you're only going to tell us after getting answers? Anyway, a one-liner, assuming your numbers are space separated:
    perl -anE '($s,$F[1])=($F[1],$F[1]-$s);say "@F"' <your-file>