http://www.perlmonks.org?node_id=153514

Fellow monks,
I had a task to do in Perl yesterday, and it was a simple one.

I had a 25,000-word cracking dictionary file I downloaded, and I wanted to split it up by word length (My motivation is to do with cryptic crosswords).

I just wanted to put all the 10-letter words into a file called 10.words and so on.

So I wrote it the following very dumb way. I knew it was dumb, but I knew it would work.

while(<>){ chomp($_); $len = length($_); open(OUTPUT,">>${len}.words"); print OUTPUT "$_\n"; close(OUTPUT); }

And you've got to admit, it was quick to code.

Then, tortured by how dumb it was, I came back to the problem and figured something else out -- once I'd checked that I could have an array called "@1" and an array called "@2" and so on -- for a while I was convinced that was illegal, though I can't say why.

This is the better way:

while(<>){ chomp($_); $len = length($_); if($longest < $len){ $longest = $len; } push(@{$len},$_); } $"="\n"; for($x=1;$x<=$longest;$x++){ open(WORDS,">$x.txt") || die "$!"; print WORDS "@${x}"; close(WORDS); }

Who wants to guess how much smarter the second was than the first?

The first way took 212 seconds (on a computer with a 333MHz chip) and the second took two seconds.

I just thought you might be interested, or have comments.
--

($_='jjjuuusssttt annootthhrer pppeeerrrlll haaaccckkeer')=~y/a-z//s;print;