in reply to appending to a file

Sometimes I just love doing homework :) If you plan on using this for a class, you'd better make sure you understand everything I've used. You wouldn't want a prof to ask "what does _that_ do?" and you end up blubbering a "I don't know what _that_ does".

#!c:/perl/bin/perl -w $|++; use strict; use Fcntl ':flock'; print "Enter new student's name: "; chomp( my $student = <STDIN> ); open my $fh, '+<', 'students.dat' or die "open failed: $!"; flock $fh, LOCK_EX or die "flock failed: $!"; my $found = 0; while (<$fh>) { $found = 1 if /^\Q$student\E$/i; } print $fh $student, "\n" unless $found; close $fh;

Replies are listed 'Best First'.
Re: Re: appending to a file
by davido (Cardinal) on Feb 26, 2004 at 23:54 UTC
    Each line of the input file is probably going to look something like:

    John Doe\n

    And your regex: /^\Q$student\E$/ will never match any line in that file, because it doesn't allow for the trailing newline. Thus, $student will always get printed, even if the name already exists. F


    Dave

      Did you even try running my script? If you had, you'd have seen that it works just fine. Notice the anchor I used. '$', not '\z'. So the match works just fine thank you.

        thanks so much it work fine