I am writing a script that randomly chooses an IP from an array, then tries to make an IO::Socket connection to it. I want to wrap the socket connection in
alarm() to keep it from hanging forever if something goes wrong. I don't want the whole script to die from the SIGALRM, so I'm writing a signal handler for it.
The problem is, I want the handler to use some variables from outside the handler. I can't pass them as arguments, and I don't want to make them globals. (The reason for no globals is that I want this sub to eventually be a fully-encapsulated object method.)
One solution I had thought of was making the handler local inside the sub (a nested sub). Is this the best way, or is there a better way to accomplish this task?
Here's my code so far (which is currently broken):
#!/usr/bin/perl
use strict;
use warnings;
$|++;
use Carp;
my $info = $ARGV[0] || 'string_of_data';
print outer($info);
sub outer {
use IO::Socket;
my @ips = ('xxx.xxx.xxx.xx0','xxx.xxx.xxx.xx1','xxx.xxx.xxx.xx2');
my $port = xxxx;
### $SIG{INT} = \&buh_bye; ### per ikegami
### $SIG{ALRM} = \&fallback; ### per ikegami
local $SIG{INT} = \&buh_bye;
local $SIG{ALRM} = \&fallback;
### srand; ### woops, thanks again ikegami
my $index = int(rand(scalar @ips));
alarm(5);
my $sock = IO::Socket::INET->new($ips[$index].':'.$port);
$index = fallback() unless ($sock);
alarm(0);
die "$! ($ips[$index])\n" unless ($sock);
print $sock "$info$/";
sysread $sock, my ($text), 10000;
close($sock);
print "ok ($ips[$index])\n";
return $text;
}
sub fallback {
my $signame = shift;
print +($signame) ? "Caught SIG$signame! " : "$! ";
print "($ips[$index])\nTrying fallback host ";
$index -= 1;
print "($ips[$index])\n";
$sock = IO::Socket::INET->new($ips[$index].':'.$port);
return $index;
}
sub buh_bye {
my $signame = shift;
die "\nCaught SIG${signame}!\nIP: $ips[$index]\n";
}
---
It's all fine and dandy until someone has to look at the code.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.