Need help with openFile

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chanshaw
    New Member
    • Nov 2008
    • 67

    Need help with openFile

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

    Code:
    #!c:\Perl\bin\Perl.exe
    use CGI qw/:standard/;
    use constant TRUE => 1;
    use constant FALSE => 0;
    use warnings;
    
    my $fileName = "guessingGame.csv";
    my $numGuesses;
    my $randomNumber;
    my $number = param('guessedNumber');
    
    print header,
    	start_html('Guessing Game'),
    		h3('Pick a number between 1 & 100'),
    		start_form,
    			"Number: ",textfield('guessedNumber'),p,
    			submit,
    		end_form;
        hr;
    
    	if(param())
    	{
    		if(validateGuess())
    		{
    			print "Your guess is: ",em(escapeHTML($number)),p,
    			hr;
    		}
    	}
    	
    	print end_html;
      
    sub validateGuess()
    {
    	if(($number == /^\d+$/) ||($number <= 0 )|| ($number > 100))
    	{
    		print "Please enter a digit between 0 and 101";
    		return FALSE;
    	}
    	else
    	{
    		$randomNumber = getRandomNum();
    		return TRUE;
    	}
    }
    
    sub getRandomNum()
    {
    	load();
    	my $generatedNumber = int(rand(101));
    	print "\nGenerated Number:  $generatedNumber\n";
    	return $generatedNumber;
    }
    
    sub load()
    {
    	open (FH, $fileName) || die(print "Could not open file!");
    	while (<FH>) 
    	{
    		chomp;
    		print "$_\n";
    		print "$randomNumber";
    	}
    	close (MYFILE); 
    }
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    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.

    Comment

    Working...