Not relevant to your performance issues but your chomp; statements inside the two for loops are not doing anything useful. Without an argument, chomp acts on $_ whereas you want it to act on your loop variables. So do chomp $element; and chomp $inside_elem in the outer and inner loops respectively.