วันพุธที่ 8 สิงหาคม พ.ศ. 2550

HACK#50 การเขียนโปรแกรม Google Web API ด้วยภาษา Perl

บทนี้เป็นสคริปต์ง่ายๆ ซึ่งจะแสดงให้เห็นพื้นฐานการเขียนโปรแกรม Google Web API ด้วย Perl และเป็นการแนะนำส่วนที่เป็นพื้นฐานสำคัญ ซึ่งเป็นส่วนที่มีการใช้มากสุดในหนังสือเล่มนี้

การแฮ็กส่วนใหญ่ในหนังสือเล่มนี้จะใช้ภาษา Perl เป็นหลัก ซึ่งรายละเอียดเพิ่มเติมจะแตกต่างกันไป แล้วแต่วิธีการแฮ็ก แต่โดยส่วนใหญ่แล้วจะเป็นการส่งค่าผ่าน Google Web API รวมทั้งการแสดงผลลัพธ์เป็นหลัก สำหรับใน Hack #50 นี้เป็นส่วนที่เป็นพื้นฐานสำคัญ ในการที่จะทำให้คุณได้ทราบถึงวิธีการพัฒนาแอพลิเคชันที่น่าสนใจและซับซ้อนมากยิ่งขึ้น สำหรับท่านที่ยังไม่มีวิธีการ หรือขั้นตอนในการทดสอบที่เตรียมเอาไว้ในใจก่อนหน้านี้ เนื้อหาใน Hack#50 นี้น่าจะเป็นจุดเริ่มต้นที่ดีในการทดสอบผลการทำงานผ่าน Google Web API เนื่องจากในแฮ็กนี้จะเป็นการส่งคำสั่งค้นหาไปยัง Google และแสดงผลลัพธ์ของคำสั่งนั้นออกมานั่นเอง

โค้ดตัวอย่าง

#!/usr/local/bin/perl

# googly.pl

# A typical Google Web API Perl script

# Usage: perl googly.pl

# 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 googly.pl \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 ->

doGoogleSearch(

$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

print

join "\n",

$result->{title} || "no title",

$result->{URL},

$result->{snippet} || 'no snippet',

"\n";

}

Running the Hack

การใช้งานก็เพียงรันสคริปต์นี้ที่ command line โดยใส่คำถามที่คุณต้องการลงไปแทน query keywords

$ perl googly.pl “query keywords”

ผลลัพธ์

ข้างล่างนี้เป็นตัวอย่างผลลัพธ์ที่ได้จากการรันสคริปต์ ซึ่งในการค้นหาครั้งแรกเราไม่ได้ระบุคำถามในการค้นหาลงไป ซึ่งทำให้ไม่มีผลลัพธ์ใดๆออกมา นอกจากข้อความว่า Usage: perl googly.pl ส่วนครั้งที่สองระบุคำว่า learning perl เป็นคำถาม ซึ่งก็ได้ผลลัพธ์ตามที่เห็นข้างล่างนี้

% perl googly.pl

Usage: perl googly.pl

% perl googly.pl "learning perl"

oreilly.com -- Online Catalog: Learning

Perl, 3rd Edition

http://www.oreilly.com/catalog/lperl3/

... 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

...

Amazon.com: buying info: learning perl (2nd Edition)

http://www.amazon.com/exec/obidos/ASIN/1565922840

... learning perl takes common programming idioms and expresses them

in "perlish"
terms. ... (learning perl,

Programming Perl, Perl Cookbook).

ดูเพิ่มเติม

การวนลูปเพื่อเพิ่มจำนวนผลลัพธ์ [Hack #51]

0 ความคิดเห็น: