http://qs321.pair.com?node_id=348799


in reply to How to modify/delete records in a flat-file database?

If you still need to use a CSV (which may be useful if it needs to be human-readable, for example) there is another method. Instead of thinking of changing one row in a file, you should think of it as changing the entire file. This may be a bit backwards compared to some of those fancy CPAN modules, but it's simple and it works.

Basically, what you'd want to do is read the entire file into a series of hashes, using the username as the key. Then you would make whatever change needs to be made to the hash in memory, and write the entire file back to the disk. This would have the effect of changing one line but would really be overwriting the entire file.

I recently wrote a CGI script that will allow changes to be made to a CSV remotely, so I'll borrow code from it to illustrate this solution, based on your given data set.
my @names; my %nums; my %stats; my %oses; my $i=0; my $csv="data.csv"; # read data from $csv open CSV, $csv or die; flock(CSV, 1); while (<CSV>) { chomp; ($name,$num,$stat,$os) = split(':'); $nums{$name} = $num; $stats{$name} = $stat; $oses{$name} = $os; $names[$i] = $name; $i++; } close CSV; #make necessary changes to %nums, %stats, %oses as required, or delete + an entry entirely # write data over $csv open (CSV, '>', $csv) or die; flock(CSV, 2); foreach my $name(@names) { print CSV join(':',$name,$nums{$name},$stats{$name},$oses{$name}). +"\n"; } close CSV;
There are more efficient ways, of course, but this will get the job done.