The string/regex you compare to should encompass as much as possible of the whole output string:

# need to chomp the file input before testing $found = 1 if /^$student\t$studentAge$/;

Personally, I would suggest using eq because this isn't really a regex problem. You are searching the file for an exact match to a string which is completely known. A regex might be suitable if you were looking for, say, a name followed by an age: /^\s*\w+\s+\d+\s*$. But testing for string equality fits what you are doing, and is faster than a regex.

my $text = "$student\t $studentAge\n"; my $found = 0; while (<$fh>) { $found = 1 if $_ eq $text; }

Your example here deals with the input of a single name and age. If you're dealing with homework, that might be all you need. Or, if you're writing a web interface to soemthing, you'll obtain your information one at a time. In other cases, however, you would receive many names, many ages. In that case, I would suggest reading the file into a hash, so you can quickly and easily test each new value.

# Read the file into a hash # my %dataFileContains; open my $fh, 'students.dat' or die "open failed: $!"; my $line; while ($line = <$fh>) { chomp $line; $dataFileContains{$line}++; } close $fh; # # Read in and test each value, caching those which # will be output. # my @output; my ( $name, $age ); while ( ($name, $age ) = getStudentData() ) { my $outLine = "$name\t$age"; push @output, $outLine unless $dataFileContains{$outLine}; } # # Output the data. # if ( scalar @output ) { open my $fh, '>>students.dat' or die "open failed: $!"; foreach ( @output ) { print $fh, "$output\n"; } }

--
TTTATCGGTCGTTATATAGATGTTTGCA


In reply to Re: regex issue by TomDLux
in thread regex issue by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.