in reply to Filter and writing error log file

Split your script into several subroutines and you'll easily see how to do what you want. Also, perltidy will make your program look less messy.