On Thu, 2004-05-27 at 15:09, Jose Alves de Castro wrote: > 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 :-)
That was simply neat. I had read in a perl book ' there is always a shorter way in perl '. I think this proves it. But to think of it there is one hitch suppose my string is 'god' Assume $word = "good" $r = qr/^[god]+$/ then $r would match $word. Can you think of a good work around ? Thanks Ram -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>