in reply to file handling error

It's hard to understand your code if you let a random number generator be in charge of indentation. How can you ever code that way?

Anyway, ignoring all the pointless juggling you're doing with arrayrefs if all you're passing into a sub is a single string (and the verbose way of unpacking the ref), never mind the double matching, it seems you're writing to a file (after opening it twice!), then reading from it before flushing or closing.

I've given up on trying to understand what you possible are trying to do. I suggest you remove the code, and start over.