in reply to script debug

I suspect that you're unclear on what
$line =~s/\n$//; $line =~s/^\n//;
will really do, and why. Take a second pass through perlre, paying particular attention to $ and its relationship to \n.