Mojolicious as a client
Mojolicious isn’t just a framework for websites. It’s also a web client. Until Mojolicious, the only reasonable general-purpose web client for Perl was LWP::UserAgent (Library-WWW for Perl). That library has been around for a long time, has many things built on top of it, and is actively maintained.
I like writing web clients, and I’ve used LWP::UserAgent for years. I’m used to it, know its insides, and can get things done. I didn’t have any reason to switch until I saw Marcus Ramberg’s presentation on Mojolicious at the Nordic Perl Workship. After playing with it a bit, I think I like it much more. There's a richer interface, more functionality, and I think even the internals are nicer.
Mojolicious is another framework from Sebastian Riedel, whom you may remember from other frameworks. Sebastian wanted to create a self-contained web thingy that would handle everything you might need for the "HTML5 web". It wasn’t just going to fetch resources for you, it was going to parse it and let you walk it too. And, almost all of this was going to happen out of the box without add-ons. I think he, and the rest of the Mojolicious community, got it mostly right.
A simple program to print a webpage looks similar to what I would do with LWP::UserAgent:
It gets more interesting when I want to do something with the response. I can immediately access the HTML DOM, for instance:
I can also do more fancy processing. I can extract the titles of articles in the feed for blogs.perl.org. The
I might even do parallel requests with Mojo::IOLoop. Since I’m fetching pages from MetaCPAN, I needed to install IO::Socket::SSL. This bit of code grabs the latest version number for each module (there’s a better way to do this, though):
If the response isn’t HTML, but is JSON, like you would expect from AJAXy-like web thingys, you can easily handle that too. I get immediate access to the data without loading additional modules:
The ojo module lets you do these from the command line, too. It provides shortcuts. Notice that the call to
res has disappeared because the
g shortcut returns that for you:
The Mojo::UserAgent can do much more powerful things, but this should be enough to whet your appetite.