Mark Weisman wrote: > > I'm trying to read from a file, copy it's contents to another file, > then overwrite the first file. > > open (INFILE, "<myfirstfile.txt") || die "Error opening myfirstfile.$!,stopped"; > @array1 = <INFILE>; > close(INFILE); > > foreach my $rec (@array1) { > chomp($rec); > ($x,$y,$z) = split(/\|/,$rec); > if ($y ne "AK") { #this leaves one record uncopied. > open (OUTFILE, ">>mysecondfile.txt") || die "Error opening > mysecondfile.$!,stopped"; > print OUTFILE "$rec\n"; > close(OUTFILE); > }; > }; > > Normally I should just overwrite the first file with an "open", right? > > open (OUTFILE, ">myfirstfile.txt") || die "Error opening myfirstfile.$!,stopped"; > print OUTFILE "$a|$b|$c\n"; > close(OUTFILE); > > Then I can copy the other stuff back replacing the original record with > the new one I just pasted in there. > > open (INFILE, "<mysecondfile.txt") || die "Error opening mysecondfile.$!,stopped"; > @array2 = <INFILE>; > close(INFILE); > > foreach my $rec (@array2) { > chomp($rec); > open (OUTFILE, ">>myfirstfile.txt") || die "Error opening myfirstfile.$!,stopped"; > print OUTFILE "$rec\n"; > close(OUTFILE); > }; > > However, I seem to get doubles of the record left behind, the old record > does not seem to go away, what am I doing wrong?
Hi Mark. Well you're doing several things wrongly: - I had to reformat your code before I could understand what it was doing! - Always 'use strict' and 'use warnings' - Opening and closing a file to add each record is just wasteful - There's no need to remove the old record and add the new one in two steps But I think the answer to your question is that you're not identifying the record to be deleted properly. You're looking for a pipe-separated record with 'AK' in the second field, is that right? It must also have no leading or trailing whitespace. If you just put a 'print' statement in your conditional then you'll be able to see which records are being rejected, like this: if ($y eq "AK") { #this leaves one record uncopied. print "Record rejected: $rec\n"; } else { open (OUTFILE, ">>mysecondfile.txt") || die "Error opening mysecondfile.$!,stopped"; print OUTFILE "$rec\n"; close(OUTFILE); } Take a look at my program below which should do what you want. The scalar variables $a, $b and $c are undeclared, but apart from that it should compile. HTH, Rob use strict; use warnings; open INFILE, "myfile.txt" or die $!; my @array = <INFILE>; close INFILE; open OUTFILE, "> myfile.txt" or die $!; print OUTFILE "$a|$b|$c\n"; foreach (@array) { my (undef, $field2) = split /\|/; print OUTFILE $_ unless $field2 eq 'AK'; } close OUTFILE; -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]