# 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 } }