Previous Section  < Day Day Up >  Next Section

Hack 94. Program Google with the Net::Google Perl Module

A crisp, clean, object-oriented alternative to programming Google with Perl and the SOAP::Lite module.

An alternative, more object-oriented Perl interface to the Google API is Aaron Straup Cope's Net::Google ( google&mode=module). While not fundamentally different from using SOAP::Lite [Hack #93] as we do throughout this book, constructing Google API queries and dealing with the results is a little cleaner.

There are three main Google API interfaces defined by the module: search(), spelling(), and cache( ) for talking to the Google Web search engine, spellchecker, and Google cache, respectively.

To provide a side-by-side comparison to [Hack #92], the typical SOAP::Lite-based way to talk to the Google API, we've provided a script identical in function and almost so in structure.

9.11.1. The Code

Save the following script as Replace insert key here with your Google API key as you type in the code.

Mind you, you'll still need SOAP::Lite and a couple of other prerequisites to use Net::Google.



# A typical Google API script using the Net::Google Perl module.

# Usage: perl <query>


use strict;


# Use the Net::Google Perl module.

use Net::Google;


# Your Google API developer's key.

use constant GOOGLE_API_KEY => 'insert key here';


# Take the query from the command line.

my $query = shift @ARGV or die "Usage: perl <query>\n";


# Create a new Net::Google instance.

my $google = Net::Google->new(key => GOOGLE_API_KEY);

# And create a new Net::Google search instance.

my $search = $google->search( );


# Build a Google query.





# Query Google.

$search->results( );


# Loop through the results.

foreach my $result ( @{$search->results( )} ) {

 # Print out the main bits of each result.


  join "\n",  

  $result->title( ) || "no title",

  $result->URL( ),

  $result->snippet( ) || 'no snippet',



Notice that the code is all but identical to that of [Hack #92] . The only real changes (called out in bold) are cleaner object-oriented method calls for setting query parameters and dealing with the results. So, rather than passing a set of parameters to a SOAP::Lite service call like this:


      $google_key, $query, 0, 10, "false", "",  "false",

      "", "latin1", "latin1"


Set these parameters individually like this:





Not much difference, but definitely cleaner.

9.11.2. Running the Hack

Invoke the hack on the command line in just the same manner you did in [Hack #92] :

$ perl  "query keywords"

The results will be just the same.

    Previous Section  < Day Day Up >  Next Section