Reputation: 11636
I have a simple Perl script which runs as a Linux daemon using an infinite loop. It connects to a database every 10 seconds to execute a process.
while (1)
{
# THIS LINE WILL KILL THE SCRIPT IF IT FAILS
my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password");
. . . do something . . .
sleep (10);
}
I have two questions:
Upvotes: 0
Views: 592
Reputation: 10090
I'm a bit puzzled:
my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password");
should not normally die if it can't connect. Normally it should return an Error Code instead of a db-handle. Only if you use RaisError will it die / throw an exception.
my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password",
{ RaiseError => 1});
See the DBI man-page
Upvotes: 5
Reputation: 212248
From Programming Perl:
sub try (&@) {
my($try,$catch) = @_;
eval { &$try };
if ($@) {
local $_ = $@;
&$catch;
}
}
sub catch (&) { $_[0] }
try {
die "phooey";
} catch {
/phooey/ and print "unphooey\n";
};
Upvotes: 1
Reputation: 118128
This attempts to connect at 10 second intervals, not every 10 seconds, as William Pursell noted:
while (1)
{
# THIS LINE WILL KILL THE SCRIPT IF IT FAILS
my $DB;
eval {
$DB = DBI->connect("dbi:Sybase:server=myserver","user","password");
};
if ( my $ex = $@ ) {
warn $ex;
next;
}
# do something with $DB
continue {
sleep 10;
}
}
See also Object Oriented Exception Handling in Perl, is it worth it? and How can I cleanly handle error checking in Perl?
Upvotes: 8