in reply to Random lines from a file for a quiz
Looks like you're on the right track, I would suggest using some more Perlish syntax ... for instance rather than print and exit when the open fails, use die and make sure to print the $! variable because it will contain why it died. Also you're using a while loop to put the file into an array but Perl can do that for you automagically. Finally alway use strict and possible warnings as they will help you to debug.
I would probably tackle it like this:
use strict; use warnings; "print "This program will ask the user random questions from a file un +til all the questions have been answered.\n"; open(QUESTFILE, 'questions.txt') or die "Couldn't open questions.txt: +$!\n"; my @questions = <QUESTFILE>; # slurps up the entire file close(QUESTFILE);
Before I continue, your answer file confuses me... opening it with > overwrites it. And it looks like you are trying to read from it but then you don't do anything with its contents that I can see. I'm going to assume you just want to append the answers.
# this opens the answers file for append open(ANSFILE,">>answers.txt") or die "Couldn't open answers for append +ing: $!\n"; # rather than a while loop and a variable just use a foreach # loop wi +th a range ... $_ will contain the number foreach(1 .. 10) { print $questions[ int( rand( scalar(@questions) ) )]; my $ans = uc(<STDIN>); print ANSFILE $ans; } close(ANSFILE); exit;
The only thing about this code is that it has the potential to ask the same question twice. You might use a hash to keep track of which questions you've already asked but I'll leave that as a excersise for you :)
Hope that helps!
Chris
|
|---|