Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: search and replace with a variable

by davido (Cardinal)
on Apr 09, 2014 at 15:27 UTC ( [id://1081676]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1081676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (3)
As of 2024-04-19 20:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found