in reply to Line number problem with foreach

You need to use a while rather than a foreach here. The foreach slurps the entire file into an array, then sets $_ to each element of the array in turn... not what you want. The while(<$fh>) reads one line at a time and sets $_ to that line.