opendir(DIR,$somepath); my %todelete; while( $file = grep /[^.]/, readdir DIR ) { if ( !exists( $todelete{$file} ) and some_test( "$somepath/$file" )) { $todelete{$file} = undef; ( my $otherfile = $file ) =~ s/this/that/; $todelete{$otherfile} = undef; } } unlink "$somepath/$_" for ( keys %todelete );