Hi, I have a simple program that ask for a four digit number and then multple questions and writes the input to a text file, so I have a text file with multple lines of information and each line starts with a four digit number. I now want to check that when a four digit number is entered at the command line it doesn't already exist and if it does exist I want the whole line of information to be printed to the comand line.

Can you tell me how I can do this.

Thanks in advance.

11 Years
Discussion Span
Last Post by KevinADC

what have you tried so far? You could do this a number of ways, but what I would probably do is build a hash from the text file first. Then check the entered number against the hash using the exists() function. If the exists() function returns true then the number is already in the file.


What exactly is the layout of the textfile? (post a line).

This is a line from them the text file.



This isn't homework is it? Next time please post the code you have been trying. Here is one way, assumes you only want to find if there is one match (the first one). If you want to find multiple matches just remove the line that has "last;"

chomp(my $input = <STDIN>);
open(FH,'yourfile.txt') or die "$!";
my $match = 0;
while (my $line = <FH>) {
   my ($digits) = $line =~ /^(\d+),/;
   if ($input == $digits) {
      print $line;
      $match = 1; 
unless ($match) {
   print "The four digits were not found in the file$/";
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.