467,081 Members | 1,150 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,081 developers. It's quick & easy.

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.

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
  • viewed: 974
Share:
2 Replies
KevinADC
Expert 2GB
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
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.

Similar topics

3 posts views Thread by hivie | last post: by
4 posts views Thread by Michi | last post: by
1 post views Thread by Bud Dean | last post: by
5 posts views Thread by robinsiebler | last post: by
3 posts views Thread by Aaron | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.