A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Timing out a call to a remote service in Perl

#!/usr/bin/perl

use strict;
use warnings;

select STDERR; $| = 1;
select STDOUT; $| = 1;

my $server = 'remote server';

my $timeout = 3;
my $retries = 3;
my $retry = 1;
my $con = 0; # connection object
my $err; # error message
while (not $con and not $err and $retry <= $retries) {
    print "starting block...\n";

    eval {
        print "eval'ing\n";
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm $timeout;
        # make connection to server
        sleep $timeout + 1; # fake
        # if we reached here, the connection was successful
        alarm 0;
    };
    if ($@) {
        if ($@ eq "alarm\n") {
            # timed out
            print "Timed out $retry time(s) connecting to $server\n";
        }
        else {
            print "died unexpectedly\n";
            $err = $@;
            $err =~ s' at /[\w\./]+\.pm line \d+$'' if $err;
        }
    }
    else {
        print "No problem!!!\n";
        $con = 1;
    }
    $retry++;
}


print "ERROR: $err\n" if $err;

print "finished. connection = '$con'\n";