Like from a phone number..
Just for fun (and well, my wife asked me for it).
Easily converted to CGI
#!/usr/bin/perl -w
#Numbers to letters v2
use strict;
my $count = 0;
my $wlist = "/usr/dict/words";
open (WLIST, "<$wlist") || die "Unable to open $wlist: $!";
my @words = <WLIST>;
my %nums =( #numbers to letters
1 => ["L"],
2 => ["A","B","C"],
3 => ["D","E","F"],
4 => ["G","H","I"],
5 => ["J","K","L"],
6 => ["M","N","O"],
7 => ["P","Q","R","S"],
8 => ["T","U","V"],
9 => ["W","X","Y","Z"],
0 => ["O"],
);
print "Please enter the numbers - between 2 and 9\n";
print "Note that 1's will convert to L's and 0's to O's\n: ";
chomp (my $key=<STDIN>);
my @keys=split "",$key;
my $length = scalar @keys;
#call the sub, let it know which letter in the word we are looking at,
#which letters we are looking for and the wordlist -
#this keeps going until there are no more numbers to check
#this is seperate to give it the "first" list (faster this way)
my $words = &get_wrds($count,$nums{shift @keys},\@words,$length);
++$count;
foreach (@keys){
$words=&get_wrds($count,$nums{$_},$words);
++$count;
}
foreach (@{$words}){
#there should only be a couple of N letter words left..
print "Found $_\n";
}
sub get_wrds{
my $pos = shift; #position in the word
my $list = shift; #list of letters
my $wlist = shift; #list of words
my $lng = shift; #length
my @words; #temp storage
foreach my $let(@{$list}){
foreach (@{$wlist}){
chomp;
if ($lng){ #get rid of irrelevant words
next unless length $_ == $lng;
}
if ( index(uc $_,$let,$pos) == $pos){
push @words,$_;
}
}
}
return \@words; #return matches
}
FWIW this is a revisit of a very early script of mine. That one was plain ugly - due to indentation the foreach loops were marching right off the page :-) - plus it only did 4 numbers. I was curious when I first finished this as to which of the 2 was faster. Imagine my surprise when I discovered that the ugly bad code that I had written before was much quicker. Hence some of the optimizations (ie: passing references instead of arrays, skipping non N length words etc). This code now runs faster :-).