Perl - Warning Someone When Things Go Astray

Thanks to modularity, all we need to do to accomplish the task of writing incorrect guesses (failed attempts) to a log file is to add a new subroutine and modify the &good_word() subroutine.  We have all of the information that we need:

sub good_word {
	my($somename,$someguess) = @_;			# name the parameters
	$somename =~ s/\W.*//;				# zap everything after the first word
	$somename =~ tr/A-Z/a-z/;			# lowercase everything
	if ($somename eq "larry") {			# should not need to guess
		return 1;				# return value is true
	}
	elsif {($words{$somename}) || "mfd") eq $someguess) {	
		return 1;				# return value is true
	}
	else {
		&log_failure($somename, $someguess);
		return 0:				# return value is false
	}
}

sub log_failure {
	my($somename,$someguess) = @_;			#name the parameters
	open(LOG, ">>failures.log") || die "Can't open failures.log:  $!";
	print LOG "bad news:  $somename guessed $someguess\n";
	close (LOG) || die "Can't close failures.log:  $!";
}

Notice the open, which has a redirection symbol (>>) in the filename.  This symbol is a special indication that we are appending to a file.  The next statement, a print, shows that a filehandle (LOG) between the print keyword and the values to be printed selects that filehandle for output, rather than STDOUT.  This means that the message will be written to the output file (failures.log) that we've opened.  Finally, we close the filehandle.

For the next lesson, let's change the definition of the secret word filename slightly.   Instead of just the file named wordslist, let's look for anything in the current directory that ends in .secret.  In a UNIX shell, you could say

	echo *.secret
to get a brief listing of all of filenames with the extension .secret

What do you suppose the programming elements are that will allow you to do this in Perl?

See you next lesson!