foreach $ip(@ip) { last if /^#/; # ALready has a hash . Note - LAST exists this loop next unless /\b$ip\b/i; # No match - so try the next item print $out "#"; last; # Remember to exit loop after one successful match } print $_; # Print onloy once.