On Oct 5, 9:09 am, [EMAIL PROTECTED] (Robert Hicks) wrote: > The scenario: I have a file with ship id numbers. It gets updated > several times a day (by database query) and I want to find all the > "new_ships" that have been added to it. > > sub incremental_update { > print "Doing incremental update.\n"; > open $FH, '+<', $ships_file or croak "Cannot open $ships_file!\n"; > > # Get all the ships in it > my @ships = do { local $/; <$FH> };
Are you aware each element of @ships has a newline attached? Is that what you want? > my %seen = ( ); > my @new_ships = ( ); There is no need to initialize arrays/hashes to ( ) explicitly. Perl does that automatically. > > foreach my $item (@ships) { $seen{$item} = 1 } > > # Getall the LLY_NUMS from the table > $sql = qq{ SELECT LLY_NUM FROM AMVER_VESS WHERE ONPLOT_FLAG = 'T' }; > $sth = $dbh->prepare( $sql ); > $sth->execute or die "Can't execute SQL statement: $DBI::errstr\n"; > > while ( my @row = $sth->fetchrow->array ) { > foreach my $lly_num (@row) { This is redundant. You have only one column in your SELECT clause. Therefore @row will only contain one element. Eliminate one of the loops, and make this: while (my ($lily_num) = $sth->fetchrow->array()) { > unless ( $seen{$lly_num} ) { > # it isn't in %seen, so add it to @new_ships > push( @new_ships, $lly_num ); > } > } > print $FH "@new_ships\n"; > } > close $FH; > > } > > I just want to make sure my logic is right on this. If $lly_num isn't in > the %seen hash then it gets added to the @new_ships array. Then all the > new ships are written to the file. Yes. > A secondary question: When opening the file is +< correct if I want to > write back to it or should I use +>> ? Neither. See `perldoc -f open`: You can put a '+' in front of the '>' or '<' to indicate that you want both read and write access to the file; thus '+<' is almost always preferred for read/write updates--the '+>' mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable length records. Just open the file once for reading, read whatever you need, and then open the file again for writing (or appending), and print whatever you want to print. Paul Lalli -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/