Re: Use of -i inplace option
- From: "Paul Lalli" <mritty@xxxxxxxxx>
- Date: 3 Oct 2006 11:25:50 -0700
David Harmon wrote:
I try to modify a file in place with
perl -i.bak myfunc.pl data.txt
but instead of modifying in place, I get output to the screen
and a zero-length data.txt. The original data.txt is renamed
to data.txt.bak as expected.
What should my command line be?
I'm using perl v5.8.8 built for MSWin32-x86-multi-thread
Binary build 819 [267479] provided by ActiveState
Windows XP.
Simplified myfunc.pl is:
for (<>) {
print;
}
It has nothing to do with your command line and everything to do with
your code. The special magic of the $^I variable (or -i command line
switch) apply only to files read via the
while (<>) { }
construct. Your for(<>) {} construct doesn't work with it. My *guess*
as to the reason for this is that because for reads all lines from the
file at once, by the time it starts actually processing the file, the
magic of $^I has already been expended, and STDOUT has been reselected.
That is, $^I only changes the default output filehandle while <ARGV>
is still being read. As soon as it's exhausted, STDOUT becomes the
default filehandle again. Because you didn't have any print lines
while the new file was select()'ed, no text was written to that file.
On a related note, NEVER use the for (<>) {} construct. Ever. You are
attempting to process a file line-by-line, which is good, but you're
reading all the lines into memory at once, and keeping them there for
the duration of the loop.
for my $line (<$fh>) { }
is simply this in disguise:
my @all_lines = <$fh>;
for my $line (@all_lines) { }
Whereas the while(<>) {} construct reads one line, processes it,
discards it, and reads the next line.
Paul Lalli
.
- Follow-Ups:
- Re: Use of -i inplace option
- From: David Harmon
- Re: Use of -i inplace option
- References:
- Use of -i inplace option
- From: David Harmon
- Use of -i inplace option
- Prev by Date: Use of -i inplace option
- Next by Date: Re: perl flawed or my fault
- Previous by thread: Use of -i inplace option
- Next by thread: Re: Use of -i inplace option
- Index(es):
Relevant Pages
|