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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.