Thursday, January 10, 2008

Some Perl

A buddy of mine sent me a Perl question on AIM. He wanted to count words from STDIN. That is, he wanted to have snippet of Perl that would count the frequency of each word. Presumably he intends to use it in some larger application.

I helped him with his version, then thought about it a little more, realizing I could write something a little shorter, albeit not very efficient. My solution looked something like this:


use strict;

my @words = <>;
chomp @words;
my %count = map {
my $word = $_;
$word => scalar grep {$_ eq $word} @words;
} @words;
print "$_ was seen $count{$_} times\n" foreach (sort keys %count);

I was actually kind of proud of that. I know, it's not terribly efficient to have grep inside map, but you gotta admit there's a certain elegance to it...


Shan said...

You know what, bro? You've got the ultimate inside joke, there.

And when I saw your post title the first thing I thought was "he's spelled 'purl' wrong."......

Gwen said...

Am trying to come up with something witty, but can't, as I just don't know what the #%&@ I'm talking about. I'm only leaving this comment to let you know I was here.

But then, flunkies don't need to understand what's going on, they just need to shut up and grate the cheese, while nodding and gazing in adoration. I've got that down pat, anyway.

Ames said...

Oh, shoot, Shan. I thought that was Purl. I've been trying to figure out why none of those abbreviations were in my knitting books. I thought maybe he was using an archaic form or something. And, then I could not figure out why there was no picture of his WIP.