compute total from a text file

Hi,

I've encountered a problem with a perl and ksh script that totals a certain field in a text file. The computed total of the script is 295540304 but the expected is 297959288, a 2 million difference. The KSH script reads from bottom to top, and the discrepancy started on line 47 (1279th MAN segment from the bottom)

PERL script:
my $Sum;
my $addend1 = $ARGV[0];
my $addend2 = $ARGV[1];

$Sum = $addend1 + $addend2;
print $Sum;

KSH script:
TheSum=0
i=1
while [ $i -le 1302 ]
do
Addend=$(cat test.20051219101007.fin | grep MAN | cut -c 18-32 | tail -$i)
TheSum=$(ComputeSUM.pl $TheSum $Addend)
echo $TheSum
i=`expr $i + 1`
done

the test file is at:

not sure why there was a discrepancy, but it started at line 1279. i tried it using values of 50000, to check if there is a limitation to max value but it computed perfectly

please help

Your script has a lot of problems. Try this:

#/usr/bin/ksh
TheSum=0
while read Code Addend ; do
        [[ $Code = MAN* ]] && ((TheSum=TheSum+Addend))
done < test.20051219101007.fin
echo $TheSum
exit 0
$ ./scr2
297959288
$

The particular problem that attracted your attention is caused by the statement that starts out "Addend=$(". As you crawl from the end of the file towards the beginning, you are trying to store more and more data in the variable Addend. Eventually you overflow it and get unpredictable results.