如何在不退出脚本的情况下捕获错误?

时间:2013-11-18 17:17:52

标签: perl

当对等端口未侦听时,以下脚本退出。我不希望它存在而是需要继续尝试。我知道下面的'die'会导致这种情况,但有没有更好的方法来捕获错误而不退出。

my $socket = new IO::Socket::INET (
    PeerHost => $properties{peer_host},
    PeerPort => $properties{peer_port},
    Proto => 'tcp',
);
die "cannot connect to the server $!\n" unless $socket;
while(1){

 #send something to the port
}

输出:

cannot connect to the server Connection refused

2 个答案:

答案 0 :(得分:0)

die的替代方案可能会有所帮助:http://perldoc.perl.org/Carp.html

warn

http://perldoc.perl.org/functions/warn.html

答案 1 :(得分:0)

您可以使用warn

my $socket = new IO::Socket::INET (
    PeerHost => $properties{peer_host},
    PeerPort => $properties{peer_port},
    Proto => 'tcp',
);
warn "cannot connect to the server $@\n" unless $socket;
while(1){

 #send something to the port
}