#!/usr/bin/perl

use WWW::Mechanize;

$| = 1;

my $mech = new WWW::Mechanize();

my $search = $ARGV[0];
my $string = $ARGV[1];

# get results from google
print "Searching $search on google... ";
$mech->get('http://www.google.com');
$res = $mech->submit_form(fields => {q => $search});
die "Probs contacting google\n" unless $res->is_success();
print "done.\n";

print "Searching $string inside results... ";
# parse results from google;
my $found = 0; 
my $page  = 1;

while ($found == 0){
	my $content = $mech->content();
	# parse page for string in title
	while ($content =~ /<a class=l.*?>(.*?)<\/a>/gsi){
		my $title = $1;
		if ($title =~ /$string/si){
			$found = 1;
			print "String \"$string\" found at page $page\n";
			print "$title\n";
			last;
		}
	}

	next if $found;	
	# if nothing is found, load next page
	# ***NOTE***: the string "Successive" is the Italian equivalent for
	# the string "Next" in google.com results. You have to change it if 
	# you want the script to work on non-italian systems!
	$res = $mech->follow_link( text => "Successive");
	die "No more links at page $page, search ended\n" unless $res;
	die "Probs following NEXT link\n" unless $res->is_success();
	$page++;
	print ".";
}