By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,178 Members | 987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,178 IT Pros & Developers. It's quick & easy.

Searching a file for text

P: 2
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.

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/perl
  2.  
  3. print "Hello, I am Betrayal and may I ask your name?\n";
  4. $name = <STDIN>;
  5.     chop $name;
  6. print "Alright then $name I shall guess your age!\n";
  7.  
  8. $y = "n";
  9.  
  10. while($y =~ /n/) {
  11.     $guess = int(rand(50));
  12.     print "Are you $guess? <Y/N>\n";
  13.     $y = <STDIN>;}
  14.  
  15. if($y =~ /y/) {print "I win!\n"}
  16.  
Jul 7 '08 #1
Share this Question
Share on Google+
2 Replies


KevinADC
Expert 2.5K+
P: 4,059
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:

Expand|Select|Wrap|Line Numbers
  1. open(FH , 'file.txt') or die "$!";
  2. while (<FH>) {
  3.    if (/frank/) {
  4.       you found it so do something
  5.    }
  6. }
  7. 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.
Jul 8 '08 #2

P: 2
Thank you for the advice hope it helps =]]
Jul 8 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.