This puzzles me and I don't really have any good ideas how to debug it. What could possibly make it behave like this?
I may be totally wrong on this as I have absolutely no experience with Perl and how it behaves but as far as I looked at the code, the CMDLOG file stream was already used in function on line ~3000. However the file stream is being created in line ~5000. Maybe the runtime doesn't even have access to the variable yet. Maybe move the function a bit down.