in reply to open input files once

There is, indeed, no need at all for the first loop. You don't need to initialize $output with empty arrays before replacing those empty arrays with real ones.