I think what you're talking about is an in-place edit. Here is why in-place edits are difficult; file systems don't facilitate growing or shrinking files from the middle. It's almost always just at the end where a file size is allowed to change. So if you want to replace 'bar' with 'bart' somewhere other than the end of the file, you have a problem.

The simplest way to solve this problem is by avoiding it. And one good way to avoid it is to open your input file, open an output file, and copy the data from the input file to the output file, while making the change. When done, move the output file to replace the input file.

So a general framework might look like this:

open my $in, '<', 'infile.txt' or die $!; open my $out, '>', 'outfile.txt' or die $!; while( my $line = <$in> ) { $line =~ s/example/replacement/; print $out $line; } close $in; close $out or die $!; rename 'outfile.txt', 'infile.txt' or die $!;

You've got two additional issues worth mentioning; First, you seem to be dealing with CSV, so you should be working with Text::CSV, Text::CSV_XS, or DBD::CSV with DBI. Don't solve your problem some fragile homebrewed way when there's a well-tested CSV tool (several) available.

Second, you seem to be working within a CGI environment. That means your script could be invoked several times at once from several web requests. That means you need to deal with flock to prevent race conditions. This set of slides from Mark Jason Dominus is a helpful introduction: File Locking Tricks and Traps.


Dave


In reply to Re: search and replace with a variable by davido
in thread search and replace with a variable by tronmason

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.