Use of -i inplace option

D

David Harmon

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;
}
 
P

Paul Lalli

David said:
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
 
D

David Harmon

On 3 Oct 2006 11:25:50 -0700 in comp.lang.perl.misc, "Paul Lalli"
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 (<>) { }

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top