in reply to modifying a text file on Win32

You've opened your file for reading and writing, which is good, but after you read in the file, you don't seek back to the beginning. So, you're appending the modified lines at the end of the existing contents.

The easiest way to modify a file in place is probably to use Perl's nifty in-place editing feature. Here's one way of doing it:

#!/usr/bin/perl -i.bak # in-place editing; save the original file with a .bak extension use Win32::Console; use strict; open(STDERR, ">error.log") or die "Can't open error log: $!\n"; my $con = Win32::Console->new(); $con->Mode(ENABLE_WINDOW_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT); $con->Display; $con->Write("Please enter the agent ID number: "); chomp(my $port = <STDIN>); $con->Write("The port number to use is $port.\n"); #Debug stuff, this +works { local @ARGV = "c:\\blah.txt"; # set up a temporary @ARGV for in-place editing while (<>) { s/serverport 111$/serverport $port/; print; } }
All you have to do is use the -i switch and put the name of the file(s) to change in @ARGV. Then you can just read in lines with <>, modify them, and print them back out.

See perlrun for more about Perl's -i command line switch.

Replies are listed 'Best First'.
Re: Re: modifying a text file on Win32
by Anonymous Monk on Aug 13, 2001 at 07:38 UTC
    Thanks for the suggestions. I'm still getting the same error with your code as I mentioned in my post below - can't find c:\blah.txt, no such file or directory. But the file is definitely there...Maybe it's a Win32 thing??

    Thanks,

    Glenn

      Just checking, the file really is in the root directory of the C drive?

      You might try specifying the file simply as 'blah.txt' (without any path), chdir-ing to the directory containing 'blah.txt', and running your script from there.

        Yes, the file is really at the root of C: I also tried moving it to the c:\perl\bin directory, as that's where I'm executing the script from (via "perl c:\console.pl"). Didn't seem to make a difference...