package UrbanDictionary;
use strict;
use LWP::Simple;
use HTML::TreeBuilder;

sub whitewash { local $_ = shift; s/^\s+//; s/\s+$//; y/ //s; $_; }

sub dict
{
  my $word = join '+', @_;

  my $html = get("http://www.urbandictionary.com/define.php?term=$word");
  die "urbandictionary.com http fetch error" unless $html;

  my $parser = HTML::TreeBuilder->new;
  $parser->ignore_unknown(0);
  my $tree = $parser->parse_content($html);

  my (@words, @defs, @examples);
  for ($tree->look_down(_tag => qr/^(div|td)$/)) {
    my $c = $_->attr('class') or next;

    push @words, whitewash($_->as_text) if $c eq 'word';
    push @defs, whitewash($_->as_text) if $c eq 'definition';
    unless (wantarray) {
      for (@defs) {
	return "$words[0]: $_";
      }
    }
    push @examples, whitewash($_->as_text) if $c eq 'example';
  }

  map { "$words[$_]: $defs[$_] (Usage: $examples[$_])" } (0 .. $#defs);
}

#printf "@ARGV: %s\n", scalar UrbanDictionary::dict @ARGV; exit;
#print "$_\n" for UrbanDictionary::dict @ARGV;

1;

