Searching a file for text

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AvianAzure
    New Member
    • Jul 2008
    • 2

    Searching a file for text

    So far I have a script that attempts to guess your age (after you give it your name) with random numbers, no necessarily effective but it does the job. What I'm currently trying to do is modify the script so that it will write your name to a file and save the age in corolation to the name so that in the future when someone puts in their name if the name is already in there it'll search for the name and pull up the age linked to it. My question (for the moment) is how do I get Perl to search for the name in the file? I'll put up the script that this originated with so you can possibly understand better.

    Code:
    #!/usr/bin/perl
    
    print "Hello, I am Betrayal and may I ask your name?\n";
    $name = <STDIN>;
        chop $name;
    print "Alright then $name I shall guess your age!\n";
    
    $y = "n";
    
    while($y =~ /n/) {
        $guess = int(rand(50));
        print "Are you $guess? <Y/N>\n";
        $y = <STDIN>;}
    
    if($y =~ /y/) {print "I win!\n"}
    Last edited by numberwhun; Jul 8 '08, 02:36 AM. Reason: Please use code tags
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    To write to a file look into the open() function. To read through a file and find some data you will also use open() to open the file and "while" to read it line by line to find what you want:

    Code:
    open(FH , 'file.txt') or die "$!";
    while (<FH>) {
       if (/frank/) {
          you found it so do something
       }
    }
    close FH;
    That is not exactly how you should do it. It depends on how you store the name and age in the file. Look up the open() function for now.

    Comment

    • AvianAzure
      New Member
      • Jul 2008
      • 2

      #3
      Thank you for the advice hope it helps =]]

      Comment

      Working...