CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Can it update to another flat file?

 



thuyduong
Novice

Jan 6, 2003, 12:57 PM

Post #1 of 2 (713 views)
Can it update to another flat file? Can't Post

Hi all,

I have 2 flat file database:

1. Record A.txt

Name|SerialNumber|PartNumber|Location|Addeddate|Expiredate
TD|123456|321-23-2345|H1|10/22/2002|01/05/2003

2. Record B.txt
SerialNumber|AddedDate|Expiredate|Phone|Email
123456|01/06/2003|06/01/2003|456-1234|someone@where.com

How can I write a script to search serial number in record B.txt and replace AddedDate|Expiredate fiield in Record A.txt with AddedDate|Expiredate in Record B.txt

Now Record A.txt will be
Name|SerialNumber|PartNumber|Location|Addeddate|Expiredate
TD|123456|321-23-2345|H1|01/06/2003|06/01/2003

Do you think we can do that in perl ?? Please help.

Thanks


davorg
Thaumaturge / Moderator

Jan 7, 2003, 1:54 AM

Post #2 of 2 (705 views)
Re: [thuyduong] Can it update to another flat file? [In reply to] Can't Post

I really don't think this is an "intermediate" question. It's pretty basic stuff.

You can have as many filehandles open as you want (well, there are probably operating system limits), so the code would go something like this (this is untested):

Code
#!/usr/bin/perl 

use strict;
use warnings;

my $id = shift; # assume id passed on command line

open FILEB, '/path/to/B.txt' or die "B: $!\n";
while (<FILEB>) {
next unless /^$id\|/; # ignoe line that don't start with our id

my ($add, $expire) = (split /\|/)[4,5];

open FILEA, '/path/to/A.txt' or die "A: $!\n";
open NEWA, '>/path/to/A.txt.new' or die "New A: $!\n";

while (<FILEA>) {
if (/\|$id\|/) {
my @rec = split /\|/;
@rec[1, 2] = ($add, $expire):
$_ = join ('|', @rec);
}
print NEWA, $_;
}
close FILEA;
close NEWA:
}

rename '/path/to/A.txt.new', '/path/to/A.txt';

It might be easier to write usng something like Tie::File.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives