in reply to or with a block

I want to opendir, then if it fails, I want to execute a block of code, rather than just warn or die. It seems like this should work:

The word you're looking for is "do". Try   opendir(CLEANPATH, $path) or do { ... }; This still leaves you with a flow-of-control issue. You still need a closedir() if the opendir() succeeds. (Yeah, you can neglect this in a short script, though coding as if each script could be long-running has benefits.) For this, I prefer to be a do

if ( opendir(CLEANPATH, $path) ) { ... closedir(CLEANPATH); } else { ... }

Replies are listed 'Best First'.
Re: or with a block
by Abigail-II (Bishop) on Jun 03, 2002 at 11:13 UTC
    The use of next in the original code suggests that it's inside a loop. In that case, you can make Perl automatically deal with closing the directory.
    for my $path (...) { # Or a while opendir my $dir => $path or do { warn ...; next; } ... something with $dir ... }

    Abigail

Re: Re: or with a block
by GhodMode (Pilgrim) on May 31, 2002 at 19:07 UTC
    Perfect! I like your method. I tried the do first, but I got a "BAREWORD" error for the closedir argument when the directory could not be opened. (I'm using strict). Thanks, Vince