Google Translate using Perl

In perl, there is a package called WebService::Google. You can use this package to translate from one language to any.

The use on this package is simple, just like when you are translating your language in In this article, I’ll give an explain how to use WebService::Google package to translate from any language to English.

In your package manager, install the WebService::Google package. Then in your code, add following line :

use WebService::Google::Language;

For testing, we will just translate the word using command prompt by typing

perl word1 word2 word3 …

First, we configure the service. We can specify the language to translate at the configuration of the service, or we can also just let the service detect the language. If you wish to detect language, you can use this configuration to the service :

$service = WebService::Google::Language->new(  ‘referer’ => ‘http://translator.local/’ ,  ‘src’  => ”,  ‘dest’    => ‘en’,);

As we can see, the source language is not specified, so the service must detect the language on its own. If you want to specify, just define the src. For example, I want to translate from Indonesia to English, so my configuration is :

$service = WebService::Google::Language->new( ‘referer’ => ‘http://translator.local/’, ‘src’     => ‘id’,    ‘dest’    => ‘en’,);

Then the service will translate the word from Indonesia to English.

Then we loop for each word in @ARGV ( the arguments when we run perl ). The Code will look like this :

foreach $s (@ARGV){

	$result = $service->translate( $s );
	if ($result->error) {
		printf "Error code: %s\n", $result->code;
		printf "Message:    %s\n", $result->message;
	else {
		print "We are translating ".$result->language . " to English \n";
		print "Query : ".$s . "\n";
		print "Translation : ".$result->translation . "\n";

Take a look at the code. We loop every word in ARGV then we translate each of them. If you not specify the language source, then ” $result -> language ” will return any detected language. The result of the translation can be seen on $result -> translation.


5 thoughts on “Google Translate using Perl

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s