The basic problem with updating any disk file is that since it is fundamentally a sequential device (processes things in a serial order), you cannot just modify something in the middle of a single file. You cannot read and write to the same file at the same time when using variable length records. The easy solution for this problem is to read all of the file's data into memory. If the data needs to changed, then re-write the entire file. You can use either an array or a hash to store the data in memory.
Past this issue, the problems with your code are legion. The use of a while(1) loop is just not appropriate here. That sort of thing appears in applications like servers. Here, you should strive to put the condition that causes the loop to exit in the while () condition. Improper loop design is at the root of this confusing mess. All of this labeled redo: stuff just goes away if the loop is designed correctly. Indenting and spacing are important in programming style.
Another way to code this problem:
#!usr/bin/perl -w use strict; my %scores; print "Current Scores for each player:\n"; print "#Tries\tName\n"; open FILE, '<' ,"high_scores.dat" or die "can't open high score file $ +!"; while (<FILE>) { chomp; my ($score, $name) = split ',',$_; print "$score\t$name\n"; $scores{$name}=$score; } close FILE; print "Starting the guessing game...I've picked a number between 1 and + 100\n"; my $goal = int(rand(100)) + 1; my $guess=0; my $count=1; while ( (print "Enter your guess: "), ($guess= <STDIN>) !~ m/\s*(quit|exit)\s*$/ ) { next if $guess =~ /^\s*$/; # just reprompt for blank lines # does not increment $count chomp $guess; if ($guess =~ m/\D/) { print "Only numbers are allowed!\n"; next; } if ($guess <1 or $guess>100) { print "Guesses must be between 1 and 100!\n"; next; } if ($guess < $goal) { print "Your guess is too low!\n"; } elsif ($guess > $goal) { print "Your guess is too high!\n"; } else #$guess == $goal { print "Hurray! You've got it in $count tries!\n"; print "Enter your name: "; my $name = <STDIN>; chomp $name; if (exists $scores{$name}) { print "Previous Score for $name was $scores{$name}\n"; } $scores{$name}=$count; #update current score open FILE, '>' ,"high_scores.dat" or die "can't open high score + file $!"; foreach (sort{$scores{$b} <=> $scores{$a}}keys %scores) { print FILE "$scores{$name},$name"; } close FILE; $count = 1; print "Playing again, enter quit or exit to stop\n"; next; } $count++; } print "Thanks for playing the game.\n";
In reply to Re: Random numbers and substitution
by Marshall
in thread Random numbers and substitution
by hasnainzeenwala
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |