summaryrefslogtreecommitdiff
path: root/023/ch3.pl
blob: 2dd84376b2b0ab9a4d7206dc1d2dda1c9ec565af (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env perl
#
# Write a script to use Random Poems API. This is the easiset API, I have come
# across so far. You don’t need API key for this. They have only route to work
# with (GET).
#
# (https://www.poemist.com/api/v1/randompoems)
################################################################################

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';
use autodie;

use HTTP::Request;
use LWP::UserAgent;
use JSON qw<decode_json>;
use Time::HiRes qw<sleep>;

my $ua = LWP::UserAgent->new();
$ua->agent("gramos's script for perlweeklychallenge.org");

my $uri = 'https://www.poemist.com/api/v1/randompoems';
my $resp = $ua->request(HTTP::Request->new('GET', $uri));
my $content = decode_json($resp->content);
my $poem = $content->[0];
my $poet = $poem->{'poet'};

$|++;
sub typewrite {
    my $text = shift;
    foreach my $i (0 .. length($text) - 1) {
        my $char = substr($text, $i, 1);
        print $char;

        my $sleep =
            $char eq ',' ? 0.2 :
            (grep { $_ eq $char } qw<- : ( )>) ? 0.3 :
            $char eq ';' ? 0.4 :
            $char eq '.' ? 0.5 :
            (grep { $_ eq $char } qw<! ?>) ? 0.6 :
            $char eq "\n" ? 0.7 :
            0.06;
        sleep($sleep);
    }
}

typewrite sprintf "%s", $poem->{'title'};
sleep(0.2);
typewrite sprintf "\nby %s\n\n", $poet->{'name'};
printf "(%s)", $poem->{'url'};
typewrite(sprintf "\n\n%s\n", $poem->{'content'});