John Bokma Perl
freelance Perl programmer

Google calculator interface

Example program | 4 comments

The Perl program on this page is an example, for educational purposes only, of how to use the LWP::UserAgent and HTTP::Request::Common modules to download a web page and extract information from it. It doesn't use the Google API since the Google calculator is not yet supported by this API. Hence, this program might be and infringement on the use of Google.

Note that I set the num (number of results) parameter to one in the query string in order to reduce traffic in case the expression can not be calculated by Google and search results are returned. Setting it to zero also works but I didn't bother to find out which returned result page was the shortest. Also, I use a simple regular expression to extract the information. For more complex processing of a result a parsing module is recommended.

The Perl program is very barebone and improvement on the code is left as an exercise to the reader. Note that setting the User-Agent header is necessary, otherwise 403 Forbidden is returned since the default user agent string LWP::UserAgent sends to Google triggers a simple automated request detection system that Google uses.

# gcalc.pl - Google calculator example
#
#  Copyright, 2004-2005 By John Bokma, http://johnbokma.com/
#
# This script is for educational purposes only.
#
# $Id: gcalc.pl 1088 2008-09-30 19:11:55Z john $ 

use strict;
use warnings;

use URI::Escape;
use LWP::UserAgent;


unless ( @ARGV ) {

    print "usage: gcalc.pl expression\n",
          "    example: gcalc.pl 75 kg in stones\n";
    exit( 1 ) ;
}

my $url = 'http://www.google.com/search?num=1&q=' .
    uri_escape( join ' ' => @ARGV );

my $ua = LWP::UserAgent->new( agent => 'Mozilla/5.0' );
my $response = $ua->get( $url );

$response->is_success or
    die "$url: ", $response->status_line;

my $content = $response->content;

my ( $result ) = $content =~ m|<td nowrap><font size=\+1><b>(.*?)</b></td>|;

if ( $result ) {

    $result =~ s/<sup>/^/g;
    $result =~ s/&times;/x/g;
    $result =~ s/<.+?>//g;

    print "$result\n";

} else {

    print "No result\n";
}

Example of usage

Examples of Perl program usage and output:

gcalc.pl 14 inch in mm
14 inch = 355.6 millimeters

gcalc.pl seconds in a year
1 year = 31 556 926 seconds

gcalc.pl speed of light
the speed of light = 299 792 458 m / s

gcalc.pl one acre
one acre = 4 046.85642 m^2

gcalc.pl seconds in a century
1 century = 3.1556926 x 10^09 seconds

gcalc.pl 3 * PI / sin(3)
(3 * PI) / sin(3) = 66.7855543

gcalc.pl 75 usd in euro
75 U.S. dollars = 60.1829562 Euro

Note that Google search also supports currency converting.

Further reading

Please post a comment | read 4 comments, latest by Jokel | RSS feed