in reply to search and replace with a variable
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
|
|---|