#!/usr/local/bin/perl # $Id$ # # Yoshiki Kurihara # package Translate; use strict; use base qw(Class::Accessor); use WWW::Babelfish; use Jcode; __PACKAGE__->mk_accessors(qw(babelfish source destination text filter)); #Translate->new({ # source => 'English', # destination => 'Japanese', # text => 'This is a pen.', #}); sub new { my $class = shift; my $self = bless {}, $class; $self->_init(@_); return $self; } sub _init { my $self = shift; my $args = shift; $self->babelfish(WWW::Babelfish->new()); die( "Babelfish server unavailable\n" ) unless defined($self->babelfish); $self->filter( sub { my $str = shift; Jcode->new($str)->euc; } ) unless $args->{filter}; $self->source($args->{source}) if $args->{source}; $self->destination($args->{destination}) if $args->{destination}; $self->text($args->{text}) if $args->{text}; } sub translate { my $self = shift; my $result = $self->babelfish->translate( source => $self->source || 'English', destination => $self->destination || 'Japanese', text => $self->text || undef, ); die("Could not translate: " . $self->babelfish->error) unless $result; return $self->filter->($result); } package ReadLine; use strict; use Term::ReadLine; sub new { my $class = shift; my %args = @_; return bless { term => new Term::ReadLine, prompt => $args{prompt} || 'translate>', }, $class; } sub prompt { my $self = shift; $self->{term}->readline($self->{prompt}); } package main; use strict; use Getopt::Std; my %opts; getopts('s:d:h', \%opts); my @langs = qw(Chinese English French German Italian Japanese Korean Portuguese Russian Spanish); if ($opts{h}) { print <<"USAGE"; Usage: $0 [-s source] [-d destination] Chinese English French German Italian Japanese Korean Portuguese Russian Spanish USAGE exit(0); } &check_lang($opts{'s'}); &check_lang($opts{'d'}); my $readline = ReadLine->new; while(my $text = $readline->prompt) { exit(0) if $text =~ /^exit|quit$/; my $t = Translate->new({ source => $opts{'s'} ? $opts{'s'} : 'English', destination => $opts{'d'} ? $opts{'d'} : 'Japanese', text => $text, }); print $t->translate, "\n"; } sub check_lang { my $lang = shift; if ($lang) { my $has_lang = 0; for my $l (@langs) { $has_lang = 1 if $l eq $lang; } die "Can't find lang, $lang" unless $has_lang; } }