Scrabble-Dict

 view release on metacpan or  search on metacpan

lib/Scrabble/Dict.pm  view on Meta::CPAN

package Scrabble::Dict;

use base qw/Exporter/;
use LWP::UserAgent;
use strict;

our @EXPORT_OK = qw/scrabble_define/;
our $VERSION = '0.01';

my %defaults = (
  host => 'www.hasbro.com',
  uri_home => '/games/adult-games/scrabble/home.cfm',
  uri_dict => '/games/adult-games/scrabble/home.cfm?page=Dictionary/dict',
  undefined_as => ''
);

sub new {
  my $this = shift;
  my $class = ref($this) || $this;
  my %init = @_ & 1 ? die "argument hash expected" : @_;

  my $self = {
    _host         => delete $init{host}         || $defaults{host},
    _uri_home     => delete $init{uri_home}     || $defaults{uri_home},
    _uri_dict     => delete $init{uri_dict}     || $defaults{uri_dict},
    _undefined_as => delete $init{undefined_as} || $defaults{undefined_as},
  };

  $self->{_ua} = LWP::UserAgent->new(%init, cookie_jar => {});

  return bless $self => $class;
}

sub define {
  my ($self, $word) = (shift, lc shift);
  my $ua = $self->{_ua};

  my %param = (
    type => 'dictionary',
    exact => 'on',
    Word => $word
  );

  # hasbro site forces us to eat ColdFusion cookies the first time

  my $url_home = "http://$self->{_host}$self->{_uri_home}";
  my $cookie_scan = sub { $_[1] eq 'CFID' && $_[4] eq $self->{_host} };

  $ua->get($url_home) if not $ua->cookie_jar->scan($cookie_scan);

  my $url_dict = "http://$self->{_host}$self->{_uri_dict}";
  my $html = '';

  $ua->post($url_dict, \%param, ':content_cb' => sub { $html .= shift });

  return $self->scrape_definition($html, $word);
}

sub scrape_definition {
  my ($self, $html, $word) = (shift, shift, shift);

  return $1 if $html =~
    m{<div \s+ id="dict_return">
        .*?
        <span \s+ .*?>
          \Q$word\E .*? \\ \s+ (.*?)
        </span>
        .*?
      </div>}xsm;

  return $self->{_undefined_as};
}

sub scrabble_define {
  my $word = shift;
  return __PACKAGE__->new(@_)->define($word);
}

1;

__END__

=head1 NAME

Scrabble::Dict - look up words in the official Scrabble dictionary

=head1 SYNOPSIS

  # procedural interface

  use Scrabble::Dict qw/scrabble_define/;



( run in 2.067 seconds using v1.01-cache-2.11-cpan-13bb782fe5a )