in reply to cgi programming problem with perl
This looks like seriuous need for rewrite and refactoring. I'll add explanations as comments:
# for maintainability's sake: # keep this filename in one place our $database_file = 'dbfile.pdb'; # self-explanatory name sub add_person { my ($name,$surname,$phone) = @_; # a fully qualified call to open open my $dbfile, '+<' , $database_file or die "Error opening '$database_file': $!"; flock $dbfile,LOCK_SH #share this file for now or die "Error flocking '$database_file': $!"; # $dbfile is what was DBFILE before, but lexikals are # less dangerous, because the handle is not global # and you needn't locale()ize the *GLOB # using a while loop here # note explicit localization of $_! # you had two loops around the handle, which was # nonsense. This here says: while you can read data # from $dbfile # a flag indicating a duplicate was found; my $dupe = 0; while(defined(local $_ = <$dbfile> )){ # source of errors: don't forget to chomp! chomp; # use usefull variable names my ($check_name,$check_surname) = split /,/; if( $name eq $check_name and $surname eq $check_surname ){ # huston, we have a duplicate ++ $dupe; # so we can stope here last; } } # that's it if( $dupe ){ close $dbfile; return; #false, this means: the name was already in # the database } else { # now we'll write to the file, so let's lock it flock $dbfile,LOCK_EX or die "Couldn't get excl. lock ... : $!"; # go to the end of the file seek $dbfile , 0 , 2; # and add the new dataset print $dbfile "$name,$surname,$phone\n"; close $dbfile or die "Write error in '$database_file': $!"; return 1; #success } }
The code that generates output should be in another function that only invokes add_person() and uses the return value as indicator for success. Keep frontend and backend seperate! The exceptional errors (all the die - cases) must be caught differently.
You built two loops around the <DBFILE> statement, which caused the outer loop (while) to be executed exactly once, stripping the first line from the file stream and the second loop (foreach) to iterate over all following lines, btw. loading them all into memory at once, which is never a good idea. The inner loop would only finish after all lines of the file were read, which would cause the outer loop to stop, too.
--
|
|---|