Cookbook

Short, copyable fragments for talking to the outside world. Original examples only — adapt paths and URLs to your environment.

Fetch JSON (core-friendly)

use strict;
use warnings;
use HTTP::Tiny;
use JSON::PP qw(decode_json);

my $url = $ARGV[0] // 'https://httpbin.org/json';
my $res = HTTP::Tiny->new( timeout => 10 )->get($url);
die "GET $url failed: $res->{status} $res->{reason}\n" unless $res->{success};

my $data = decode_json( $res->{content} );
print JSON::PP->new->canonical(1)->pretty->encode($data);

HTTP::Tiny and JSON::PP ship with modern Perl builds; check with corelist HTTP::Tiny.

POST JSON

use strict;
use warnings;
use HTTP::Tiny;
use JSON::PP qw(encode_json);

my $url  = $ARGV[0] // die "usage: $0 URL\n";
my $body = encode_json({ source => 'perl-cookbook', ts => time });
my $res  = HTTP::Tiny->new->post(
    $url,
    {
        headers => { 'Content-Type' => 'application/json' },
        content => $body,
    },
);
die "POST failed: $res->{status}\n" unless $res->{success};
print $res->{content};

Mojo one-shot (when Mojo is installed)

use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get('https://httpbin.org/get');
say $tx->result->json('/headers/User-Agent');

Reshape a list of metrics

use strict;
use warnings;
use JSON::PP qw(decode_json encode_json);

# Expect: [ { "name": "cpu", "value": 0.4 }, ... ]
my $rows = decode_json( do { local $/; <STDIN> } );
my %by_name = map { $_->{name} => $_->{value} } @$rows;
print encode_json(\%by_name), "\n";

Time-stamp a line for logs

use strict;
use warnings;
use POSIX qw(strftime);

while (<>) {
    chomp;
    print strftime('%Y-%m-%dT%H:%M:%SZ', gmtime), "\t", $_, "\n";
}

See also