Skip to content

Instantly share code, notes, and snippets.

@xuchunyang
Created September 30, 2014 07:50
Show Gist options
  • Save xuchunyang/c56625fdf405ad79ba72 to your computer and use it in GitHub Desktop.
Save xuchunyang/c56625fdf405ad79ba72 to your computer and use it in GitHub Desktop.
ydcv in perl
#!/usr/bin/env perl
#
# ydcv in Perl
#
use strict;
use warnings;
use LWP::UserAgent;
use JSON qw( decode_json );
# Print wide character
# http://stackoverflow.com/questions/15210532/use-utf8-gives-me-wide-character-in-print
use open ':std', ':encoding(UTF-8)';
# Fetch url
my $word = shift or die "Usage: $0 word\n";
my $url = "http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoCV&key=659600698&type=data&doctype=json&version=1.1&q=" . $word;
my $ua = LWP::UserAgent->new();
my $req = HTTP::Request->new(GET => $url);
my $response = $ua->request($req);
# Parse response and display result
if ($response->is_error()) {
printf " %s\n", $response->status_line;
} else {
my $content = $response->content();
# print $content;
my $decoded = decode_json($content);
print $decoded->{'query'}, "\n";
my @explains = @{ $decoded->{'basic'}->{'explains'} };
foreach ( @explains ) {
print " ", $_, "\n";
}
}
@xuchunyang
Copy link
Author

Sample output:

~  ./ydcv.pl fake
fake
  n. 假货;骗子;假动作
  adj. 伪造的
  vt. 捏造;假装…的样子
  vi. 假装;做假动作
  n. (Fake)人名;(英)费克

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment