7

这种结构在 perl 中很常见:

opendir (B,"/somedir") or die "couldn't open dir!";

但这似乎不起作用:

opendir ( B, "/does-not-exist " ) or {
    print "sorry, that directory doesn't exist.\n";
    print "now I eat fugu.\n";
    exit 1;
};

“或”错误处理是否可能有多个命令?

编译上述内容:

# perl -c test.pl
syntax error at test.pl line 5, near "print"
syntax error at test.pl line 7, near "}"
test.pl had compilation errors.
4

2 回答 2

19

您可以随时使用do

opendir ( B, "/does-not-exist " ) or do {
    print "sorry, that directory doesn't exist.\n";
    print "now I eat fugu.\n";
    exit 1;
}

或者您可以使用如果/除非:

unless (opendir ( B, "/does-not-exist " )) {
    print "sorry, that directory doesn't exist.\n";
    print "now I eat fugu.\n";
    exit 1;
}

或者你可以一起摆动你自己的子程序:

opendir ( B, "/does-not-exist " ) or fugu();

sub fugu {
    print "sorry, that directory doesn't exist.\n";
    print "now I eat fugu.\n";
    exit 1;
}

有不止一种方法可以做到这一点。

于 2012-05-04T18:20:12.653 回答
-2

Perl 中的异常处理是用eval()

eval {
    ...
} or do {
    ...Use $@ to handle the error...
};
于 2012-05-04T18:20:29.530 回答