Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl "or" error handling: multi-statement on error possible?

Tags:

perl

This construct is pretty common in perl:

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

But this does not seem to work:

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

Is it possible for the "or" error-handling to have more than one command?

Compiling the above:

# 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.
like image 543
raindog308 Avatar asked May 04 '12 18:05

raindog308


1 Answers

You can always use do:

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

Or you can use if/unless:

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

Or you can swing together your own subroutine:

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

There is more than one way to do it.

like image 191
TLP Avatar answered Oct 06 '22 01:10

TLP