foreach $file (@filelist) { next unless file =~ /_00001\.\w+$/; # now only start for looking for a random number to replace _00001 # ... }