my @infiles = &GetINDirFiles($inpath); # instead of having an array with the outfiles use a hash for faster lookup # also remove suffix at this stage already, no need to do it again and again in the loop # you need to escape your suffix variable in \Q...\E for special characters such as the dot # only remove the suffix at the end, no need for (.*) my %outfiles = map { s/\Q$outsuffix\E$//; $_ => 1 } &GetOUTDirFiles($outpath); my $index = 0; # index used to get string position in array foreach my $infile (@infiles) { # see above re the replacement $infile =~ s/\Q$insuffix\E$//; # remove suffix to do comparation # Added by me # instead of loop through array of outfiles do hash lookup push (@delindex, $index) if exists $outfiles{$infile}; $index += 1; }