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;
}

または、if/unless を使用できます。

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 に答える