Create a gist now

Instantly share code, notes, and snippets.

@xjackk /xkcd.pl
Last active Dec 21, 2015

What would you like to do?
xkcd!
#!/usr/bin/perl
use warnings;
use strict;
use Switch;
use Modern::Perl '2014';
use LWP::Simple;
use JSON;
use Data::Dumper;
##
## Check out out the latest xkcd comic from your terminal, quickly.
## - jaaacckz1@gmail.com
##
# welcome!
&welcome;
# get latest xkcd JSON from site ~
my $xkcd = get("http://xkcd.com/info.0.json");
# json decode
my $decode = decode_json($xkcd);
# debugging purpose
# print Dumper($decode);
## Dereference JSON and print it out just like the comic
## Do the work right hurr
print "\t$decode->{title}";
print " - ";
&date;
print " " . "$decode->{day}";
print " -". " $decode->{year}\n\n";
print "\t" . "$decode->{alt}\n\n";
&news;
# ask to open image or not!
print "\tImage Link! Do you want to open it up? (y/n) ";
print "\n\t" . "$decode->{img} ";
chomp(my $choice = <STDIN>);
&image;
# welcome!
sub welcome {
print "\n";
print "\tJack's xkcd quickviewer!\n\n";
}
sub date {
my $month = $decode->{month};
switch($month) {
case 1 {print "January"}
case 2 {print "Feburary"}
case 3 {print "March"}
case 4 {print "April"}
case 5 {print "May"}
case 6 {print "June"}
case 7 {print "July"}
case 8 {print "Aug"}
case 9 {print "September"}
case 10 {print "October"}
case 11 {print "November"}
case 12 {print "December"}
}
}
# pattern matching with news to see if there is any
# "It feels like we only go backwards, baby"
sub news {
my $news = $decode->{news};
if ($news =~ /^\s\s$/) {
print " - No News! ";
} elsif ($news =~ /^w/) {
print "\t$news";
}
}
# maybe add on for other options or whatever
# just for my useage now... sorry.
sub image {
my $image = $decode->{img};
my $osname = $^O;
# args for OSX opening with "system"?
my @args = ("open", "-a", "firefox", "$image");
if ($choice eq "y") {
system("firefox", "$image");
system(@args) == 0;
} elsif ($osname eq "darwin" && $choice eq "y") {
system(@args) == 0;
} elsif ($choice eq "n") {
print "\n\tbye,jack !\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment