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).


In reply to Re: subtracting two lines in file by almut
in thread subtracting two lines in file by frank19

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.