Hi, All!
While listening to Weekend Edition Sunday, the puzzle offered up for next week made for a fun, toss-off bit of perl.
Name a well-known international food in five letters. Move the first two letters to the end. The result will be another well-known international food in five letters. What foods are these? They are both foods that originated overseas, but are now popular in the United States and around the world.
I wrote this script in about 5 minutes, but it took me about an hour to find a dictionary to help with the answer. Anyway, peruse and enjoy! Any advice of more efficient means to accomplish this is solicited and welcome!
UPDATE: I've been thinking that the substrs could be replaced with pack and unpack, and I just figured out how. UPDATE 2: I also changed the lengthy comment to pod.
#!/usr/bin/perl -w
#-*-cperl-*-
use strict;
=pod
puzzle.pl - print a list of five letter words for a puzzle answer
usage:
puzzle.pl [dictionary_file]
This script addresses the 12 August 2001 puzzle from Weekend Edition
Sunday puzzle ( http://www.npr.org/programs/wesun/puzzle/ )
Name a well-known international food in five letters. Move the first
two letters to the end. The result will be another well-known
international food in five letters. What foods are these? They are
both foods that originated overseas, but are now popular in the
United States and around the world.
We cycle through a dictionary file, either one provided on the
command line or the standard dictionary ( /usr/share/dict/words
on many *nix ). We find words that fit the above criteria and print
them out.
You'll have to do the definition legwork, unless you want to write
some tool to do that, too.
=cut
my $dictionary = $ARGV[0] || "/usr/share/dict/words";
open ( DICT, "< $dictionary" )
or die "Cannot open $dictionary: $!\n";
my %fives;
foreach ( <DICT> ) { # go through the dictionary
chomp; # strip the /n
$fives{$_} = undef # slap them into a hash
if ( length $_ == 5 ); # we only want 5 letter words
}
close DICT;
foreach my $word ( keys %fives ) { # cycle thru the 5 letter words
$_ = pack ( # put it back together
"A3 A2", ( # back-end first
unpack ( # split it, moving ahead 2
"x2 A3 X5 A2", # take 3, go back 5
$word # and take 2
)
)
);
print $word , "\t" , $_ , "\n" # print the result & orig. word
if ( exists $fives{$_} ); # if the result is a real word
}
HTH
--
idnopheq
Apply yourself to new problems without preparation, develop confidence in your ability to to meet situations as they arrise.