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

Hi, I need to add the values in column 1 together except for the last line, how can i ignore the last line in this context?
open (COM, "2_info.txt"); open (MEAN, ">" . "/2_mean_info.txt"); foreach (<COM>){ last LINE if /^d$/;?? if (/^\d+\.\d+.*/) {$value = (split /\|/, $_)[0];} $additive_GU_value += $value; $num_GU_processed++ ; } # foreach close (COM); print "Add = $additive_GU_value\n";
input
10| 20| 45| 1
thanks

Replies are listed 'Best First'.
Re: while question
by davidrw (Prior) on Jun 02, 2005 at 14:42 UTC
    with the code above, i see a few different methods:
    1. (My preferred method) Match not just on the line starting w/a number, but also having a pipe:
      if( /^(\d+\.\d+)\|/ ){ $additive_GU_value += $1; $num_GU_processed++ ; }
    2. Check the split() to see that it got a 2-element array back.
    3. Subtract off the last value. (i don't like this method)
      } # foreach $additive_GU_value -= $value; close (COM);
    4. Push the first column to an array, and at the end pop the last item before looping through and summing. This innately stores the num_GU_processed, too.
      thanks for the thoughts i extended the if loop and that seems to work fine cheers
Re: while question
by Fletch (Bishop) on Jun 02, 2005 at 14:37 UTC

    It looks like your valid data lines only match /^(\d+(?:\.\d*))\|/, so you want to only add if the line matches. What you've done is unconditionally add whatever was left in $value from the last time through your loop.

    Update: Also, read perldoc perlstyle and look into perltidy presuming that's actually how your code is formatted. Better indentation might help you visualize the flow and have helped you catch this.

    --
    We're looking for people in ATL

Re: while question
by cool_jr256 (Acolyte) on Jun 02, 2005 at 14:39 UTC
    Hope I understood your problem, but if I did, then the easiest way would be to match for the '|' which would exclude the last line....
    Just a thought..
Re: while question
by Anonymous Monk on Jun 02, 2005 at 14:34 UTC
    the funyy thing is that the answer is wrong if i dont explicity ignore the last line