我有一个简单的Perl脚本,它使用无限循环作为Linux守护程序运行。它每10秒连接一次数据库以执行一个进程。
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);
}
我有两个问题:
答案 0 :(得分:8)
这种尝试以10秒的间隔连接,而不是每隔10秒,就像William Pursell所指出的那样:
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;
}
}
另请参阅Object Oriented Exception Handling in Perl, is it worth it?和How can I cleanly handle error checking in Perl?
答案 1 :(得分:5)
我有点疑惑:
my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password");
如果无法连接,通常不会死亡。通常它应该返回错误代码 而不是数据库句柄。只有你使用RaisError才会死/抛出异常。
my $DB=DBI->connect("dbi:Sybase:server=myserver","user","password",
{ RaiseError => 1});
请参阅DBI man-page
答案 2 :(得分:1)
sub try (&@) {
my($try,$catch) = @_;
eval { &$try };
if ($@) {
local $_ = $@;
&$catch;
}
}
sub catch (&) { $_[0] }
try {
die "phooey";
} catch {
/phooey/ and print "unphooey\n";
};