Skip to content

Instantly share code, notes, and snippets.

@cabrinha
Last active September 29, 2015 19:42
Show Gist options
  • Save cabrinha/1bb5f716f88d8e9bbb60 to your computer and use it in GitHub Desktop.
Save cabrinha/1bb5f716f88d8e9bbb60 to your computer and use it in GitHub Desktop.
Urban Dictionary API JSON formatting manipulation using perl
#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use v5.20.1;
use Data::Dumper;
use Mojo::URL;
use Mojo::UserAgent;
my %commands = (
ud => sub { # Search UrbanDictionary for terms
my ($term) = $ARGV[0]; # change to @_
my $url = Mojo::URL->new( 'http://api.urbandictionary.com/v0/define' )
->query( term => $term );
my $tx = Mojo::UserAgent->new->get($url);
if ( $tx->success ) {
my $json = $tx->res->json;
my $list = $json->{list};
my @defs = map { $_->{definition} } @$list;
my $results = join " :: ", grep /\S/, map {split /\R/, $_ } @defs;
say substr($results, 0, 509), '...';
}
else {
my $err = $tx->error;
die "$err->{code} response: $err->{message}" if $err->{code};
die "Connection error: $err->{message}";
}
},
);
$commands{ud}->();
:: OUTPUT ::
pur'-el (n) 1. Computer programming language used mostly by male virgins, between the ages of 17 and 35, who are also well versed in the Lord Of The Rings stories. :: Pratical Extraction and Reporting Language. :: :: Perl is a script programming language that is similar in syntax to the C language and that includes a number of popular Unix facilities such as SED, awk, and tr. Perl is an interpreted language that can optionally be compiled just before execution into either C code or cross-platform bytec...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment