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

Need help with openFile

P: 67
Well this is broken, I can't get it to open the file even though it does exist.

Expand|Select|Wrap|Line Numbers
  1. #!c:\Perl\bin\Perl.exe
  2. use CGI qw/:standard/;
  3. use constant TRUE => 1;
  4. use constant FALSE => 0;
  5. use warnings;
  6.  
  7. my $fileName = "guessingGame.csv";
  8. my $numGuesses;
  9. my $randomNumber;
  10. my $number = param('guessedNumber');
  11.  
  12. print header,
  13.     start_html('Guessing Game'),
  14.         h3('Pick a number between 1 & 100'),
  15.         start_form,
  16.             "Number: ",textfield('guessedNumber'),p,
  17.             submit,
  18.         end_form;
  19.     hr;
  20.  
  21.     if(param())
  22.     {
  23.         if(validateGuess())
  24.         {
  25.             print "Your guess is: ",em(escapeHTML($number)),p,
  26.             hr;
  27.         }
  28.     }
  29.  
  30.     print end_html;
  31.  
  32. sub validateGuess()
  33. {
  34.     if(($number == /^\d+$/) ||($number <= 0 )|| ($number > 100))
  35.     {
  36.         print "Please enter a digit between 0 and 101";
  37.         return FALSE;
  38.     }
  39.     else
  40.     {
  41.         $randomNumber = getRandomNum();
  42.         return TRUE;
  43.     }
  44. }
  45.  
  46. sub getRandomNum()
  47. {
  48.     load();
  49.     my $generatedNumber = int(rand(101));
  50.     print "\nGenerated Number:  $generatedNumber\n";
  51.     return $generatedNumber;
  52. }
  53.  
  54. sub load()
  55. {
  56.     open (FH, $fileName) || die(print "Could not open file!");
  57.     while (<FH>) 
  58.     {
  59.         chomp;
  60.         print "$_\n";
  61.         print "$randomNumber";
  62.     }
  63.     close (MYFILE); 
  64. }
  65.  
Feb 24 '09 #1
Share this Question
Share on Google+
1 Reply


KevinADC
Expert 2.5K+
P: 4,059
write the line like this:

open (FH, $fileName) or die "Could not open file: $!";


$! will return the operating system error ('file not found' or whatever the error is).

The file must be in the same directory as the script since you are only using the filename to open it with, or you must change directory to where the file is before opening it or you could use the full disk path to the file in the open() function.
Feb 24 '09 #2

Post your reply

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