Forum Moderators: coopster & phranque

Message Too Old, No Replies

Updating a file in PERL

         

ramoneguru

7:00 pm on Apr 23, 2006 (gmt 0)

10+ Year Member



I have a file that has the following items in it:

name pin balance so some data looks like this:

dave 1234 56
sam 2345 84.45
someguy 4567 -45.69
etc....

Now I was wondering, if I wanted to update the last number for a specific name how would I go aabout doing that? Am I stuck w/ rewriting the old file to a new "updated" file then renaming it?

This will find the name of the person whose "balance" I want to update but how do I update it, then write it to
the "new" file?
Note: $in_name will be the name I want to update, $in_pin will be the number next to the name. Example:
sam has pin 2345 and balance 84.45
$old_file is the file with the names/numbers
open(PFILE, "<$old_file") ¦¦ die "Can't open $info_list: $!";
open(NEW, ">$new_file") ¦¦ die "Can't open $new_file: $!";

select(PFILE);
$¦ = 1;
select(STDOUT);

while(defined ($line = <PFILE>) ) {
($name, $pin, $balance) = split( / /, $line);
if (($name eq $in_name) && ($pin == $in_pin)) {
$found = "YES";
}

--Nick

bennymack

7:21 pm on Apr 23, 2006 (gmt 0)

10+ Year Member



Here's some free fish:


use 5.008;
use strict;
use warnings;
use Tie::File;

my $pfile='pfile.txt';
my $in_name = $ARGV[0] or die "usage: $0 name pin balance";
my $in_pin = $ARGV[1] or die "usage: $0 name pin balance";
my $in_bal = $ARGV[2] or die "usage: $0 name pin balance";
warn '$in_pin=',$in_pin,' $in_name=',$in_name,' $in_bal=',$in_bal;

tie my @array, 'Tie::File', $pfile or die;

for my $line( @array ) {
my($name,$pin,$bal)=split(/\s/,$line);
warn '$pin=',$pin,' $name=',$name,' $bal=',$bal;
if( $name eq $in_name and $pin eq $in_pin ) {
print "FOUND: $in_name:$in_pin=$bal, UPDATING balance to $in_bal\n";
$line="$name $pin $in_bal";
}
}
untie @array;

ramoneguru

8:41 pm on Apr 23, 2006 (gmt 0)

10+ Year Member



Great, thanks.
--Nick