in reply to Useless Program

I don't have time to try this, but this code should work.
#!/usr/bin/perl -w use strict; open (FILE, "+<users.txt") or die "File not found\n"; #Open the file + in read/write mode flock FILE,2; # It is good practice to lock a file you will write to +. my $name = ''; my $yn = ''; print "Enter your name--> "; chomp ($name = <STDIN>); while (<FILE>) { chomp; if (/^$name/) { print "Your name was already found\n"; exit; } } print "Name not found. Would you like to add it? (y/n)--> "; chomp ($yn = <STDIN>); if ($yn eq 'y') { print FILE "$name\n"; #Since we went through the file we can n +ow print to the end of the file close FILE; #Closing a file will unlock it }else { print "FINE!\n"; ; } print "end.\n";

Replies are listed 'Best First'.
RE: Re: Useless Program
by lhoward (Vicar) on Jun 01, 2000 at 17:16 UTC
    One problem with this code is if you're adding a name that is the prefix of a name already in the DB it will think that it is alrady there. Try running this code and adding les after leslie has already been added. Better to use eq instead of a regular expression in your compare since you are looking for an exact match. It will be faster too:
    if ($_ eq $name) {
    instead of
    if (/^$name/) {
RE: Re: Useless Program
by husker (Chaplain) on Jun 02, 2000 at 00:14 UTC
    Should you be holding a file lock around user input? I was always taught to lock a file only when you aren't potentially waiting the for the user to type something. Perhaps the FLOCK should be moved to right before the WHILE loop (and perhaps you only want to lock it when you know you need to write to it .. in that case, move the FLOCK to precede the 'print FILE' statment).
RE: Re: Useless Program
by cei (Monk) on Jun 01, 2000 at 23:05 UTC
    You have to be careful there... You're currenly only explicitly closing the file if they choose "y". Move the close FILE; to outside of the if/then/else statement for best results... (perhaps not a big deal, but I've found that if I'm not careful with my file closing, my server gets cranky...)