in reply to Better Way to Search Large File.
You will have to go through the entire file, there is no way around that. Unless you can calculate the exact spot you want to modify upfront.
The Perl CookBook gives several strategies for updating a file.
1. Read from the original file, output to a temporary file. Make the changes you want to the temporary file. Rename the temporary back to the original once you’re done. A snippet to explain the idea:
use strict; use warnings; my ($old, $new); open(OLD, "< $old") or die "can't open $old: $!"; open(NEW, "> $new") or die "can't open $new: $!"; while (<OLD>) { # Some logic... print NEW $_ or die "can't write $new: $!"; } close(OLD) or die "can't close $old: $!"; close(NEW) or die "can't close $new: $!"; rename($old, "$old.orig") or die "can't rename $old to $old.orig: $!"; rename($new, $old) or die "can't rename $new to $old: $!";
2. Use the -i and -p switches to Perl. This also creates a temporary file but Perl takes care of the file manipulation.
There are a few more like: "Updating the file in place without a temporary file" and "Updating a Random-Access File" but in your case (a small csv file) this seems like overkill to me.
Bless the CookBook!
BTW You have a lot of if/elsif statements. This can probably be improved upon. You might want to take a look at the Switch. Or use the ternary operator to improve the readability.
A last remark: there are many modules around on CPAN to work with CSV data. This might be the simplest/most elegant solution of all:-)
Hope this helps.
|
|---|