If you'd had 'use strict' at the top of the script you'd have spotted that '$firstlineFlag' is not the same as '$firstLineFlag'. Also the declaration of '$firstlineFlag' increments an uninitialised variable (which would have been caught with '-w'). Once it runs cleanly with 'strict' and 'warnings', you'll be in a better position to find out what the problem is with your algorithm. (I suspect that it will be OK when '$firstlineFlag' is changed to '$firstLineFlag').
rdfield