Perl - Many Secret Word Files in the Current Directory

Perl has what is called a filename glob which works much like <STDIN>, in that each time it is accessed, it returns the next value:  successive filenames that match the shell pattern, in this case *.secret.  When there are no additional filenames to be returned, the filename glob returns an empty string (OK, undef again).

So if the current directory contains karee.secret and jason.secret, the $filename is jason.secret on the first pass through the while loop (the names come out in alphabetically sorted order).  On the second pass, $filename is karee.secret.  And there is no third pass because the glob returns an empty string the third time it is called, perceived by the while loop to be false, causing an exit from the subroutine.

Pulling out the init_words() definition again, here's a small chunk of code to look for anything in the current directory that ends in .secret:

sub init_words {
	while (defined($filename = glob("*.secret"))) {
		open (WORDSLIST, $filename) || die "can't open $filename: $!";
		if (-M WORDSLIST >= 7.0) {
			while ($name = <WORDSLIST>) {
				chomp ($name);
				$word = <WORDSLIST>;
				chomp ($word);
				$words($name) = $word;
			}
		}
		close (WORDSLIST) || die "couldn't close $filename: $!";
	}
}

First, I wrapped a new while loop around the bulk of the routine from the previous version of the program on which we've been working.  The new part there is the glob function described above.

Within the while loop, the file is opened and verified that it's recent enough (less than seven days since the last modification).  The recent enough files are scanned through as before.

Note that if there are no files that match *.secret and are less than seven days old, then the subroutine will exit without having set any secret words into the %words array.  That means that everyone will have to use the secret word mfd.  Oh, well.  (For real code, we would have added some check on the number of entries in %words before returning, and die'd if it weren't good.  We'll see a way of doing this in a later lesson.)

Well, all this power is going to the head of the Chief Director of Secret Word Lists.  Now he wants a report of all the secret words currently in use and how old they are.  We're going to set aside the secret word program for a moment, and write a reporting program for the Director.

What programming elements do you suppose that we will need to write a reporting program?  Can we re-use any of the elements from the secret word program?

See you next lesson!