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; } #### my %outfiles = map { /(.*)\Q$outsuffix\E$/; $1 => 1 } &GetOUTDirFiles($outpath); my @infiles = grep { /(.*)\Q$insuffix\E$/; not exists $outfiles{$1} } &GetINDirFiles($inpath); print "@infiles\n"; #### use strict; use warnings; sub GetINDirFiles { my ($path) = @_; opendir my $dir, $path or die $!; return grep {!/\_ACK_/} readdir $dir; } sub GetOUTDirFiles { my ($path) = @_; opendir my $dir, $path or die $!; return grep {/\_ACK.xml$/} readdir $dir; } # Main my $inpath = "./IN"; my $outpath = "./OUT"; my $outsuffix = "_ACK.xml"; my $insuffix = ".xml"; my $timethreshold = 900; # set time threshold in seconds (900 seconds equal 15 minutes) my %outfiles = map { /(.*)\Q$outsuffix\E$/; $1 => 1 } &GetOUTDirFiles($outpath); my @infiles = grep { /(.*)\Q$insuffix\E$/; $1 and not exists $outfiles{$1} } &GetINDirFiles($inpath); my $currenttime = time; # get current time from system (epoch time) @infiles = grep { -f "$inpath/$_" and ( $currenttime - (stat "$inpath/$_" )[9] ) > $timethreshold } @infiles; # now you have all input files w/o corresponding output file that are older than 15 minutes for (@infiles) { print "File $_ in $inpath directory was created ". ( $currenttime - (stat "$inpath/$_" )[9] )/60.0 ."minutes ago.\n"; # put your action here }