Skip to content

Instantly share code, notes, and snippets.

@leejarvis
Created May 25, 2010 11:37
Show Gist options
  • Select an option

  • Save leejarvis/413041 to your computer and use it in GitHub Desktop.

Select an option

Save leejarvis/413041 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl -w
use strict;
use warnings;
use IO::Socket::INET;
use feature qw/say/;
# Google translate
sub get($$$) {
my ($text, $langfrom, $langto) = @_;
my $data;
$text =~ s/\s+/+/;
my $query = "GET /translate_a/t?client=t&text=$text&hl=$langfrom&tl=$langto HTTP/1.1\r\n
Host: translate.google.com\r\n\r\n";
my $sock = IO::Socket::INET->new(
PeerAddr => 'translate.google.com',
PeerPort => 80,
Proto => 'tcp'
);
print $sock $query;
$data .= $_ for <$sock>;
my ($head, $body) = split "\r\n\r\n", $data;
return $body;
}
sub translate {
my ($text, $langto, $langfrom) = @_;
$langfrom ||= 'en';
$langto ||= 'en';
my $source = get($text, $langfrom, $langto);
my ($trans) = $source =~ /trans":"([^"]+)/;
say "Text:\n$text\n\nTranslation:\n$trans";
}
translate("hello there", "de");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment