Programming the Google Web API with Perl

screenshot moderate.gifscreenshot tip50.gif

A simple script illustrating the basics of coding the Google Web API with Perl and laying the groundwork for the lion's share of tips to come.

The vast majority of tips in this tutorial are written in Perl. While the specifics vary from tip to tip, much of the busy work of querying the Google API and looping over the results remain essentially the same. This tip is utterly basic, providing a foundation on which to build more complex and interesting applications. If you haven't done anything of the sort before, this tip is a good starting point for experimentation. It simply submits a query to Google and prints out the results.

The Code

# A typical Google Web API Perl script
# Usage: perl «query»
# Your Google API developer's key my $google_key='insert key here';
# Location of the GoogleSearch WSDL file my $google_wdsl = "./GoogleSearch.wsdl";
use strict;
# Use the SOAP::Lite Perl module use SOAP::Lite;
# Take the query from the command-line my $query = shift @ARGV or die "Usage: perl «query»\n";
# Create a new SOAP::Lite instance, feeding it GoogleSearch.wsdl my $google_search = SOAP::Lite-»service("file:$google_wdsl");
# Query Google my $results = $google_search -» 
 $google_key, $query, 0, 10, "false", "", "false",
 "", "latin1", "latin1"
# No results?
@{$results-»{resultElements}} or exit;
# Loop through the results foreach my $result (@{$results-»{resultElements}}) {
 # Print out the main bits of each result
 join "\n", 
 $result-»{title} || "no title",
 $result-»{snippet} || 'no snippet',

Running the Tip

Run this script from the command line, passing it your preferred query keywords:

$ perl "query keywords"

The Results

Here's a sample run. The first attempt doesn't specify a query and so triggers a usage message and doesn't go any further. The second searches for learning perl and loops through the results.

% perl
Usage: perl «query»
% perl "learning perl" -- Online Catalog: Learning 
Perl, 3rd Edition
... learning perl, 3rd Edition Making Easy Things Easy and Hard Things 
Possible By Randal L. Schwartz, Tom Phoenix 3rd Edition July 
2001 0-596-00132-0
... buying info: learning perl (2nd Edition)
... learning perl takes common coding idioms and expresses them 
in "perlish"«br» terms. ... (learning perl, 
Programming Perl, Perl Cooktutorial).

See Also