-
Notifications
You must be signed in to change notification settings - Fork 319
/
ch-3.pl
executable file
·87 lines (72 loc) · 2.16 KB
/
ch-3.pl
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env perl
use v5.26;
use strict;
use warnings;
# Turn on method signatures
use feature 'signatures';
no warnings 'experimental::signatures';
use autodie;
use Getopt::Long;
use Mojo::Util qw(url_escape);
use Mojo::UserAgent;
use Path::Tiny;
use Perl6::Slurp;
MAIN: {
my $configfile = path( $ENV{HOME} // "", ".openweathermap" )->stringify();
my ( $city_name, $city_id );
GetOptions(
"city-name=s" => \$city_name,
"city-id=i" => \$city_id,
"config-file=s" => \$configfile,
);
if ( ( !defined($city_name) ) && ( !defined($city_id) ) ) {
die("Must specify --city_name=<city> or --city_id=<id>");
}
my $apikey = get_api_key($configfile);
get_weather(
apikey => $apikey,
city_name => $city_name,
city_id => $city_id,
);
}
sub get_api_key($configfile) {
my (@lines) = grep { length($_) } slurp($configfile);
die "Config-file ($configfile) must consist of one line" if @lines != 1;
chomp $lines[0];
return $lines[0];
}
# Usage:
# apikey = Your Sendgrid API key
# city_name = Optional <city name> or <city name>,<country-code>
# city_id = Numeric City ID
#
sub get_weather(%args) {
my $url = "https://api.openweathermap.org/data/2.5/weather?";
if ( defined( $args{city_id} ) ) {
$url .= "id=" . $args{city_id};
} else {
$url .= "q=" . url_escape( $args{city_name} );
}
$url .= "&appid=" . url_escape( $args{apikey} );
my $ua = Mojo::UserAgent->new();
my $tx = $ua->get($url);
if ( ( $tx->result->code >= 200 ) && ( $tx->result->code <= 299 ) ) {
my $json = $tx->result->json;
say "Wather for "
. $json->{name} . ", "
. $json->{sys}{country} . " " . "(ID="
. $json->{id} . ")";
say " " . join( "; ", map { $_->{description} } $json->{weather}->@* );
say sprintf( " Temp: %.0fC / %.0fF", k2c( $json->{main}{temp} ),
k2f( $json->{main}{temp} ) );
return;
}
my $body = $tx->result->json;
die "Error from API endpoint: " . $body->{message};
}
sub k2c($k) {
return $k - 273.15;
}
sub k2f($k) {
return k2c($k) * 9/5 + 32;
}