Google Analytics

Thursday, May 01, 2008

Random words on command

Today I needed to generate SQL queries to populate a database table with some test data. I was making a Facebook-style search & narrow thing where, as you type, the list of options narrow based on your search string. I wanted to test the efficiency of my implementation, so I figured it would make testing easier if I used real words for the list items.

It seems a lot of people have needed to do this, so it wasn't long before I found a fairly good solution for my purposes. Here's the magic line:

perl -nle '$word = $_ if rand($.) < 1; END { print $word }' /usr/share/dict/words

I really have no idea why this works as I'm no Perl Monger. I also found that I didn't have any words at /usr/share/dict/words, since I was on an Ubuntu server install. I needed to sudo aptitude install wbritish. Incidentally, it worked on my OS X 10.5 machine too. Unix is handy.

I only needed 500 records and calling this 500 times didn't take too long. Much more and you'd probably have to modify your approach though.

No comments: