Perl "or" error handling: perhaps a multitask error message?

This construct is quite common in perl:

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

But this does not 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 "or" error handling to have more than one command?

Compilation 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.
+5
source share
2 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 / except:

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 deploy your own routine:

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 are several ways to do this.

+14
source

Perl exception handling with eval ()

eval {
    ...
} or do {
    ...Use $@ to handle the error...
};
-2
source

All Articles