# This is the translation module. It is used by saying # "require 'translation.pl';" near the start of your program. o # # Then you can &translate("any string"); # # By David Mankin package translation; use LWP::UserAgent; use Carp; $DEFAULT_TRANSLATION_DIRECTION = "fr_en"; $DEFAULT_CGI_URL="http://babelfish.altavista.com/cgi-bin/translate?"; $DEFAULT_COOKIE_URL="http://babelfish.altavista.com/"; $DEFAULT_CGI_METHOD="POST"; $DEFAULT_PROXY="http://cacheflow.cs.colorado.edu:3128"; $AGENT_NAME="FIT/0.1"; # http://babelfish.altavista.com/cgi-bin/translate? # doit=done&urltext=Eat+my+lunch&lp=fr_en my $cookie = undef; sub translate { &translate_lang($DEFAULT_TRANSLATION_DIRECTION, @_); } ## # translate_lang(string [, string, string, ...]); ## sub translate_lang { my ($lang) = shift; &setup_cookie unless (defined $cookie); my (@strings) = @_; my (@results) = (); my $ua = new LWP::UserAgent; $ua->agent($AGENT_NAME . " " . $ua->agent); $ua->proxy('http', $DEFAULT_PROXY) if $DEFAULT_PROXY; my $req = new HTTP::Request $DEFAULT_CGI_METHOD => $DEFAULT_CGI_URL; $req->content_type('application/x-www-form-urlencoded'); foreach (@strings) { my $content = &prepare_content($_, $lang); $req->content($content); my $res = $ua->request($req); if ($res->is_success) { my $content = $res->content; $content =~ s/(\n|\r|\r\n)/ /g; my $translation = &parse_results($content); push (@results, $translation); } else { warn "Couldn't retrieve results from server"; } } if (wantarray) { return @results; } else { if (@results > 1) { carp "Warning: Using &translation() for multiple arguments in scalar context"; } return $results[0]; } } ## # private setup_cookie(). # # Requests a page in order to get the cookies it returns so we can post # post to it later. # # For now, does nothign ## sub setup_cookie { } ## # private parse_results($HTML) # # Parses the results # # For now, does nothing. ## sub parse_results{ my ($html) = @_; #return $html; $html =~ s/\n//g; $html =~ s/^.*//s; #if ($html =~ /$PRE_HINT/) { # print "Matches PRE HINT\n"; #} else { # print "Does not match PRE HINT\n"; #} #if ($html =~ /$POST_HINT/) { # print "Matches POST HINT\n"; #} else { # print "Does not match POST HINT\n"; #} $html =~ m/$PRE_HINT((.|\n)*)$POST_HINT/s; return $1; return $html; } $PRE_HINT = '.*?:\s*\s*\s*\s*