On Thu, 2004-05-27 at 06:14, Jim Witte wrote: > Given a file of words W such as 'cat dog at home ...' (or perhaps read > into an array, though that would be a very large array), and a set of > letters L (a string 'aoeuidhtns' - perhaps put into a array), how would > I write a program to extract all words in W whose letters are all in L? > I'm thinking of a program to generate a string of words for a > typing-tutor program.
Hello, Jim. I'm sorry if this seems complicated, but it really isn't :-) This is a one-liner that will do precisely what you want (I hope :-) ) perl -pe 'BEGIN{$r=qr/^[asdfghjkl]+$/}split/ /;$_=join" ",grep/$r/,@_' file This particular one-liner will search for all words having only letters from the second alphabetic keyboard row (of qwerty keyboards, at least). Just to reassure you'll understand what is going on, I'm going to break the one-liner in some more readable code: ============================= #!/usr/bin/perl -pw use strict; my $r; BEGIN { $r = qr/^[asdfghjkl]+$/; } split / /; $_ = join " ", grep /$r/, @_; ============================= ...if you can call that readable... Now lets go step by step :-) ============================= #!/usr/bin/perl -pw # the -p switch will makes all input lines be printed (after being processed) use strict; # I hope you know what this is for my $r; # this will be our regular expression BEGIN { $r = qr/^[asdfghjkl]+$/; } # and on this BEGIN block we assign it to be a sequence containing characters from the mentioned row *only* split / /; # here we split the input line by spaces (and the result is put into @_) $_ = join " ", grep /$r/, @_; # and now we grep the elements that correspond to $r and join them with spaces # et voilÃ! the -p switch makes the result be printed ============================= HTH :-) jac > Jim Witte > [EMAIL PROTECTED] > Indiana University CS -- Josà Alves de Castro <[EMAIL PROTECTED]> Telbit - Tecnologias de InformaÃÃo -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>