Skip to content

Commit

Permalink
hangman: more validation (#502)
Browse files Browse the repository at this point in the history
* An empty wordlist.txt could be provided, in which case hangman should fail because no lines can be read
* Also, there was no code after the read-words loop to check if $word was actually given a value
* Rewrite read-words loop without the need for $line_num variable
* test1: create empty wordlist with "touch wordlist.txt"
* test2: create a list with 1 word: "echo hey > wordlist.txt"
  • Loading branch information
mknos committed Mar 14, 2024
1 parent baaa330 commit 2c17f79
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions bin/hangman
Expand Up @@ -73,26 +73,19 @@ print "\nTHANKS FOR PLAYING!\n";
sub get_a_word {
my $wordlist = "wordlist.txt";
my( $fh, $word );
my( $line_num ) = 1;
my( $random ) = rand();

open($fh, '<', $wordlist) or die "Could not open <$wordlist>: $!\n";
my $lines = 0;
$lines++ while (<$fh>);
die "Empty word list: $wordlist\n" unless $lines;
my $val = int($random * $lines) + 1;

close($fh) or die "Could not close <$wordlist>: $!\n";
open($fh, '<', $wordlist) or die "Could not open <$wordlist>: $!\n";

while( <$fh> ) {
if( $line_num == $val ) {
$word = $_;
chomp( $word );
last;
} else {
$line_num++;
}
}
open($fh, '<', $wordlist) or die "Could not open <$wordlist>: $!\n";
$word = <$fh> for (1 .. $val);
die "Could not find a word in $wordlist\n" unless defined $word;
chomp $word;
close($fh) or die "Could not close <$wordlist>: $!\n";
return( $word );
}
Expand Down

0 comments on commit 2c17f79

Please sign in to comment.