Okay. Here is an untested modification of the second part of your script that reads the file into an array, applies the regexes to the array and notes if any changes were made. If there were changes, creates an new file and writes the changed content to it, and finally renames the new file over the old file.
Files who do contains anything that needs modifying will be untouched and retain theor original modification timestamps, and the window for errors resulting from system failures is much reduced, though not completely eliminated.
foreach my $file (@files) {
open( FILE, '<', $file )
or die "Couldn't open $file: $!";
@data = <FILE>;
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.\c
+om/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.n
+ew: $!";
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";
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller