in reply to Random numbers and substitution
I haven't run your code either, but I did add strictures (always use strictures - use strict; use warnings;) and fixed the immediate problems. The first major problem in two places was:
while defined (...) {
which is simply broken syntax. while, for and if require () around their expression. Your while head should look like:
while (defined ...) {
I also changed your open to use a lexical file handle, to use the three parameter version of open, and checked the result. See the open line in the code below and compare it with your original version. These are things you should always do!
I removed the needless INPUT_TAKER label, but I did add a Forever label on the outermost loop to avoid retesting the contents of guess.
Having added strictures I needed to declare everything. Declaration and initialisation for scalar variables should pretty much always go together so in most cases that showed where things needed to be declared. In particular $count needs to be declared and initialised to 0 outside the guess loop.
It bothers me that the file is opened as the first thing, but is read in a deeply nested loop. Something is wrong with the logic there. In fact the entire logic of the file handling eludes me, however it looks like you would be better using YAML as a light weight database, or get really serious and learn a little real database stuff using DBD::SQLite.
My cleaned up, but otherwise uncorrected, version of your code is:
#!/usr/bin/perl use strict; use warnings; my $scoreFile = "high_score.dat"; open my $inFile, '<', $scoreFile or die "Can't open $scoreFile: $!\n"; Forever: while (1) { while (defined(my $score = <$inFile>)) { print "$score\n"; } my $num = int(1 + rand 100); my $count = 0; print "If you want to exit type 'quit' or 'exit' or leave a blank +line\n"; while (1) { $count++; print "Guess a num: "; chomp(my $guess = <STDIN>); if ($guess == $num) { print "Right!!!.\n"; print "enter your name: "; chomp(my $name = <STDIN>); while (defined(my $line = <$inFile>)) { if ($line =~ /^($name)/) { $line =~ s/\d+$/$count/; } else { open $inFile, $scoreFile or die "Can't reopen $scoreFile: $!\n"; print $inFile "$name has the score of $count\n"; } } print "You took $count chances to complete\n"; next; } last Forever if $guess =~ /^(exit||quit||\n)$/; if ($guess > $num) { print "High!!!. Go lower \n"; } else { print "Low!!!. Go higher \n"; } redo; } } print "Thank you for playing my game\n";
|
|---|