foreach my $file (@files) { open( FILE, '<', $file ) or die "Couldn't open $file: $!"; @data = ; close( FILE ); my $modified = 0; # Assume no modification foreach (@data) { # Increment the flag if changes are made ++$modified if s/servername\.aa\.company\.zzzz\.com/NEWNAME.\com/gi; ++$modified if s/\bservername\.aa\.company\.com\b/NEWNAME\.com/gi; ++$modified if s/\bservername\b/NEWNAME\.com/gi; } # If we made no modifications, # leave the original file as is if( $modified ) { # Create a new file for the modified data open( FILE, '>', "$file.new" ) or die "Couldn't create $file.new: $!"; print FILE for @data; close(FILE) # Then rename the new file over the old file, # effectively deleting the old # There is still a window of opportunity for error # if the system crashes, but it is much smaller. rename "$file.new", $file; } } print "Total Count = $ct\n";