in reply to Further On Down the Line

You're using the same var name for the file handlename and the file handle.

open($mainfilepath, "> $mainfilepath");

I don't know if that's your problem, but it definitely needs fixing. It needs error checking too, if only or die $!

Update: I guess I made a similar mistake! Fixed.