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.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.