in reply to Editing files...please help

Well, if your data file looks EXACTLY like you stated (that is, a file with only 5 lines) using a database (either the tied hash variety or something using DBI) is a little overkill.

If you know about reading and writing Perl files, try reading in the whole file, changing the part you want to change, then writing the whole file back to update it. Like this:

# Load in the whole file open (FILE, "memberpoints.txt") or die "Can't read: $!"; while (<FILE>) { chomp; ($name, $number) = split "-"; $field ($name) = $number; } # Change whatever you want $field{'vegeta'} += 6; # ..etc # Write the whole file back (replacing what was there before) open (FILE, ">memberpoints.txt") or die "Can't write: $!"; foreach (keys %field) { print FILE "$_-$field{$_}\n"; }
But, keep in mind that although something like this works fine for tiny files it doesn't scale well, so if your file gets bigger later, or needs to be accessed lots and lots of times (multiple times per second) you should look into more flexible solutions like a tied hash (SDBM, NDBM, GDBM and siblings) or a full-bore database like MySQL or PostgreSQL.

Gary Blackburn
Trained Killer

Edited: Forgot to chomp the newline. Bad newline. Bad. Added the chomp in.

Replies are listed 'Best First'.
Re: Re: Editing files...please help
by a (Friar) on Jan 28, 2001 at 11:03 UTC
    And here's a from the docs (perldoc db_file) hack to read-in your text and create a dbm:
    use strict ; use DB_File ; use vars qw( %h $k $v ) ; # hash, key value tie %h, "DB_File", "memberpoints", O_RDWR|O_CREAT, 0640, $DB_HASH or die "Cannot open file 'memberpoints': $!\n"; # Load in the whole file data file into the hash/dbm open (FILE, "memberpoints.txt") or die "Can't read: $!"; while (<FILE>) { next unless /-/; chomp; my ($name, $number) = split "-"; $h {$name} = $number; } # print the contents of the hash/dbm while (($k, $v) = each %h) { print "$k -> $v\n" } untie %h ;
    Note: you'll do this once, then you need to write your update code along the lines of:
    use strict ; use DB_File ; use vars qw( %h $k $v ) ; # hash, key value tie %h, "DB_File", "memberpoints", O_RDWR|O_CREAT, 0640, $DB_HASH or die "Cannot open file 'memberpoints': $!\n"; # update $h{vegeta} += 6; # print the contents of the db (debuggin) while (($k, $v) = each %h) { print "$k -> $v\n" } untie %h ;
    Very rough but its cold here and my fingers are getting too stiff to type.

    Update: Fruit? it really was cutnpaste ...

    a