WWW::Google::Calculator - Perl interface for Google calculator


WWW-Google-Calculator documentation Contained in the WWW-Google-Calculator distribution.

Index


Code Index:

NAME

Top

WWW::Google::Calculator - Perl interface for Google calculator

SYNOPSIS

Top

    use WWW::Google::Calculator;

    my $calc = WWW::Google::Calculator->new;

    print $calc->calc('1+1'); # => 1 + 1 = 2
    print $calc->calc('300kbps in KB/s'); # => 300 kbps = 37.5 kilobytes / second

DESCRIPTION

Top

This module provide simple interface for Google calculator.

SEE ALSO

Top

http://www.google.com/help/calculator.html

METHODS

Top

new

create new instance

calc( $query )

calculate $query using by Google and return result.

return undef when something error occurred. (and use $self->error to get last error message)

parse_html

error

return last error

AUTHOR

Top

Daisuke Murase <typester@cpan.org>

COPYRIGHT

Top


WWW-Google-Calculator documentation Contained in the WWW-Google-Calculator distribution.
package WWW::Google::Calculator;
use strict;
use warnings;
use base qw/Class::Accessor::Fast/;

use WWW::Mechanize;
use HTML::TokeParser;
use URI;

our $VERSION = '0.07';

__PACKAGE__->mk_accessors(qw/mech error/);

sub new {
    my $self = shift->SUPER::new(@_);

    $self->mech(
        do {
            my $mech = WWW::Mechanize->new;
            $mech->agent_alias('Linux Mozilla');

            $mech;
        }
    );

    $self;
}

sub calc {
    my ( $self, $query ) = @_;

    my $url = URI->new('http://www.google.com/search');
    $url->query_form( q => $query );

    $self->mech->get($url);
    if ($self->mech->success) {
        return $self->parse_html( $self->mech->content );
    }
    else {
        $self->error( 'Page fetching failed: ' . $self->mech->res->status_line );
        return;
    }
}

sub parse_html {
    my ( $self, $html ) = @_;

    $html =~ s!<sup>(.*?)</sup>!^$1!g;
    $html =~ s!&#215;!*!g;

    my $res;
    my $p = HTML::TokeParser->new( \$html );
    while ( my $token = $p->get_token ) {
        next
          unless ( $token->[0] || '' ) eq 'S'
          && ( $token->[1]        || '' ) eq 'img'
          && ( $token->[2]->{src} || '' ) eq '/images/icons/onebox/calculator-40.gif';

        $p->get_tag('h2');
        $res = $p->get_trimmed_text('/h2');
        return $res; # stop searching here
    }

    $res;
}

1;