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.


In reply to Re: modifying a text file on Win32 by chipmunk
in thread modifying a text file on Win32 by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.