@words = sort keys %{+{ map { !$common{$_ = lc $_} ? ($_, 1) : () } @w
+ords }};
and the $/ = "\n" didn't do what i wanted, but oh well.. i probably wanted $\ = ' ', but that seems broken right now too.. oh well again. | [reply] [d/l] [select] |
@words = sort keys %{+{ map { !$common{lc $_} ? (lc $_, 1) : () } @wor
+ds }};
| [reply] [d/l] |
Amazing - I'm going to have to take this off-line to work out what it is doing. map is currently top of my list of functions to try and understand. I've only ever used it based on examples in the Cookbook and then (even with the explanation) I've never been too sure of how was working. I'll print this out with the man page and look at it on the train tomorrow.
Cheers, Odud | [reply] |
#!/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] |