Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

overwriting one section of file... 1

Status
Not open for further replies.

perlone

Programmer
Joined
May 20, 2001
Messages
438
Location
US
Hi,

I have a small file called stats.txt and conatins the following:

username|gold|points|level|status|gender|email|pass|

Basically, when you run the script, it may looks like this. Let's say username is "Tom".

Tom|100|20|2|Alive|Male|host@email.com|secret

I've decided to save all this in one file to save my hosting space. Anyway, let's say i need to change the tom's gold which is 100 to 200. I know it could be done with overwriting but i don't know how to overwrite just one section. Here's a little half from my perl code:

open(F, "stats.txt");
@stats = <F>;
close(F);

foreach $stats (@stats)
{
chomp($stats);
($username ,$gold,$points,$level,$status,$gender,$email,$pass,$version)=split(/\|/,$stats);

}

I need to update one section but don't know how. Anyone have clue? Thanks again for reading this far.


 
Instead of assigning the records to a variable, you need to access the array of record directly, so you can replace the record in the array after you update it:
Code:
for my $i (0..$#stats)
{
   chomp($stats[$i];
   ($username,$gold,$points,$level,$status,$gender,$email,$pass,$version)=split(/\|/,$stats[$i]);
   # This is where you update the values
   if ($username eq &quot;Tom&quot;) {
      $gold = 200;
   }
   # Replace the record in the array
   $stats[$i] = join('|',$username,$gold,$points,$level,$status,$gender,$email,$pass,$version);
}
After you've done all your updating, you need to rewrite the file:
Code:
open(F, &quot;>stats.txt&quot;); # NOTE THE >
foreach $rec (@stats) {
   print F $rec,&quot;\n&quot;;
}
close F;
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Thanks a lot! I'll try that.
 
Oops, just noticed that there's a closing paren missing on the chomp line!
Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top