#!/usr/bin/perl -w
%common = map { lc $_, 1 } qw/ a and the /;
@words = qw/ hello there Hello hello the a A /;
@words = sort keys %{+{ map { !$common{$_ = lc $_} ? ($_, 1) : () } @w
+ords }};
print "@words\n";
haha! it's not too bad efficiency-wise. it does get rid of all temporaries and it does everything on one pass through the word list.. the only thing i'm concerned about is the list-flattening that's going on, but in reality, i'm sure it's nothing.
a more readable version would be:
%common = map { lc $_, 1 } qw/ the and a /;
@words = qw / hello Hello hello a The there /;
# lowercase all the words
@words = map { lc $_ } @words;
# shorter: @words = map { lc } @words;
# filter out common words
@words = grep { !common{$_} } @words;
# make a hash
%words = map { $_, 1 } @words
# get the sorted keys
@words = sort keys %words;
the only problem here is that we're going through the list 3 or so times. the one-liner goes through it only once. and the key to understanding the %words = map { $_, 1 } @words line is to remember that a hash can be made from a list in (key, value) order. so, map goes through the @words list and creates a new list (which it returns) consisting of (word1, 1, word2, 1, word3, 1, ...).. the %{+{ .. }} funny business was just a way to get keys to play fair. | [reply] [d/l] [select] |