perlquestion
dh
<p>Basically, I have an array called @host_array that contains information about the hosts that I want to see whether they are alive or dead. I need to check their current status against their old status and send an alert if something changes. Unfortunately, I can't seem to get the reference right. That means that when I update a value in the $task variable within sub 'pinger', it doesn't actually update the original array; just its local version of the data.</p>
<p>I want to pass a reference to the entire array to run_threaded and then a reference to a slice of that array from run_threaded to pinger.</p>
<code>
populateHosts(1);
while (1) {
run_threaded(10,\&pinger,\@host_array);
}
sub run_threaded {
my ($threads,$func_to_thread, $hosts) = @_;
my (%threads);
my $n = 0;
my $debug = 1;
my $m = $threads-1 > $#{$hosts} ? $#{$hosts} : $threads-1;
while (1) {
last if $n >= $#{$hosts}+1;
foreach my $host (@$hosts[$n..$m]) {
#Still a reference here! I can change the value of $host[x] and it will stick.
$threads{$host} = new threads $func_to_thread, $host;
}
map {
$threads{$_}->join if $threads{$_};
}
@{$hosts}[$n..$m];
# work out the next range of instances to work on
$n = $m == 0 ? 1 : $m+1;
$m = $n+$threads-1 < $#{$hosts} ? $n+$threads-1 : $#{$hosts};
}
}
sub pinger{
$task = shift;
# Create pinger
$p = Net::Ping->new("tcp");
$p->port_number($task->[4]);
if( $p->ping($task->[3], 6) ) {
print " PASS: @$task[2] ";
$task->[5] = 1;
#I want to update @host_array, but it's not a reference!
} else {
print " FAIL: @$task[2] ";
$task->[5] = 0;
#I want to update @host_array, but it's not a reference!
}
$task->[2] .= "-2";
$p->close();
}
sub populateHosts {
($init) = @_;
# DEFINE A MySQL QUERY
$query = "SELECT * FROM `sites`";
# EXECUTE THE QUERY
$db->query($query);
my $set = $db->create_record_iterator;
$i=0;
while (my $rec = $set->each) {
$host_array[$i][0] = $i;
$host_array[$i][1] = $rec->[0];
$host_array[$i][2] = $rec->[1];
$host_array[$i][3] = $rec->[2];
$host_array[$i][4] = $rec->[3];
if ($init) {
$host_array[$i][5] = $rec->[4];
$host_array[$i][8] = $rec->[5];
$host_array[$i][6] = 1;
$host_array[$i][7] = time;
}
$i++;
}
}
</code>
<p>
There are some lines that I omitted for brevity, but the function should still be similar. Thanks!</p>
<p>
By the way, the great thread function 'run_threaded' came from http://greg-techblog.blogspot.com/2009/06/threading-in-perl.html
</p>