for (my $i=0; $i < (@filenames); $i++) { should be for my $i (0 ... $#filenames) {