You have some problems with your code. For example, you have created 55 variables, some of them duplicates, while I was able to write the same code with only 21 variables. You use a hash to collect the file list and then copy its keys to an array when you only need the array. You use lists of scalars when you could just use a single array. You use three separate hashes when you could use a hash of arrays.