Skip to content

Instantly share code, notes, and snippets.

@ghedo ghedo/wr
Last active Oct 26, 2015

Embed
What would you like to do?
Translate a word using wordreference.com
#!/usr/bin/perl
# Usage: wr <term> [<dict>]
# Translate a word using wordreference.com
use strict;
use warnings;
use feature qw(say);
use JSON::PP;
use HTTP::Tiny;
use Term::ANSIColor;
my $api_url = 'http://api.wordreference.com/0.8/ae2cf/json';
my $word = $ARGV[0] || die "Usage: wr <term> [<dict>]\n";
my $dict = $ARGV[1] || 'enit';
my $url = "$api_url/$dict/$word";
my $data = do_request($url);
die color('red'), $data -> {'Note'}, "\n"
if $data -> {'Error'};
say color('green'), "Main:", color('reset');;
print_entries($data -> {'term0'} -> {'PrincipalTranslations'});
print_entries($data -> {'term0'} -> {'AdditionalTranslations'});
print_entries($data -> {'term0'} -> {'Entries'});
if ($data -> {'original'} -> {'Compounds'}) {
say color('blue'), "\nCompounds:", color('reset');
print_entries($data -> {'original'} -> {'Compounds'});
}
sub print_entries {
my $data = shift;
while (my ($id, $info) = each %$data) {
my $original = $info -> {'OriginalTerm'} -> {'term'};
my $first = $info -> {'FirstTranslation'} -> {'term'};
my $second = $info -> {'SecondTranslation'} -> {'term'};
$first .= " ($second)"
if $second;
printf "%-20s => %s\n", $original, $first
if $first;
}
}
sub do_request {
my $url = shift;
my $http = HTTP::Tiny -> new;
my $response = $http -> get($url);
die color('red'), $response -> {'reason'}, "\n"
unless $response -> {'success'};
my $data = decode_json $response -> {'content'};
if ($data -> {'Response'} and $data -> {'Response'} eq 'Redirect') {
$url = $api_url.$data -> {'URL'};
return do_request($url);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.