From 2c17f79cf01bc785953fafa8c32df997aacb69e9 Mon Sep 17 00:00:00 2001 From: Michael Mikonos <127171689+mknos@users.noreply.github.com> Date: Thu, 14 Mar 2024 13:13:49 +0800 Subject: [PATCH] hangman: more validation (#502) * 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" --- bin/hangman | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/bin/hangman b/bin/hangman index e5792ef2..03f77b7f 100755 --- a/bin/hangman +++ b/bin/hangman @@ -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 ); }