Several respondents seem to be skirting the issues here. How do I open a file for reading and writing and edit on a per line basis?

One element of this that most people foget is that it is possible to make the file smaller with search and replace operations. That means you have to truncate the file length.

Here is my code:

use IO::File qw( &SEEK_SET ); my $fh = IO::File->new("+<foo.out") or die "failed to open file: $!"; while (<$fh>) { my $line = $_; chomp $line; $line =~ s/foo/f/g; push @output, $line; } my $output = join("\n", @output); $fh->seek( 0 , SEEK_SET ); $fh->print($output, "\n"); $fh->truncate( length($output) ); $fh->close; exit 0;
Clearly, this code walks the file while building up the new output. Then we reset the file position to the beginning; write over the old file contents; and truncate the file length to be the same size as the new contents. If we don't do the last step we might have left over garbage at the end of the file.

TIMTOWTDI: Here is a non-OO way:

use Fcntl qw( &SEEK_SET ); open(FH, "+<foo.out") or die "failed to open file"; while (<FH>) { my $line = $_; chomp $line; $line =~ s/foo/f/g; push @output, $line; } my $output = join("\n", @output); seek(FH, 0 , SEEK_SET ); print FH $output, "\n"; truncate(FH, length($output) ); close(FH); exit 0;

In reply to Re: In-place editing of files (was: general perl question) by LunaticLeo
in thread In-place editing of files (was: general perl question) by cghost23

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.