Yes:
- Always use strictures (use strict; use warnings; - see The strictures, according to Seuss).
- Always use the three parameter version of open.
- Use lexical file handles: open my $in, '<', ...
- Indent controlled blocks (the body of the while loop in the sample code).
- Printing to a file you are actively reading from without an intervening seek is a bug.
Consider:
use strict;
use warnings;
my $testFileName = 'testFile.txt';
my $tempFileName = 'delme.txt';
# Create a sample file
open my $out, '>', $testFileName or die "Failed to create $testFileNam
+e: $!";
print $out <<END_STR;
be_address = remote_be_address
be_address1 = remote_be_address
be_address2 = remote_be_address
END_STR
close $out;
# The 'meat'
open my $in, '<', $testFileName;
open $out, '>', $tempFileName or die "Failed to create $tempFileName:
+$!";
while (<$in>) {
s/remote_be_address/192.168.106.60/g;
print $out $_;
}
close $in or die "Failed to close $testFileName: $!";
close $out or die "Failed to close $tempFileName: $!";
unlink $testFileName;
rename $tempFileName, $testFileName;
# Show the result
open $in, '<', $testFileName;
print <$in>;
close $in or die "Failed to close $testFileName: $!";
Prints:
be_address = 192.168.106.60
be_address1 = 192.168.106.60
be_address2 = 192.168.106.60
True laziness is hard work
|