while (<$IN>) { next if /^XYZ/ or /ZYX/ or /XZY/ or /YZZ$/; # removes all special cases where substitution should not occur s/foo/bar/g; # do something with $_ } #### foreach $file (@filelist) { next unless file =~ /_00001\.\w+$/; # now only start for looking for a random number to replace _00001 # ... }