GhodMode has asked for the wisdom of the Perl Monks concerning the following question:

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:
opendir(DIR, "$path") or { warn "Could not open directory, $path: $!\n"; next; };
but I get a syntax error near warn and the closing bracket of the block. This works, but seems sloppy:
opendir (CLEANPATH, "$path") or my $openfailed = "TRUE"; if ( defined $openfailed ) { warn "Could not open directory, $path : $!\n"; next; }
What's the best way to do it?

Replies are listed 'Best First'.
Re: or with a block
by dws (Chancellor) on May 31, 2002 at 18:35 UTC
    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 { ... }
      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

      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
Re: or with a block
by maverick (Curate) on May 31, 2002 at 18:42 UTC
    I tend to do it like this:
    unless(opendir(CLEANPATH,"$path")) { warn "$path: $!\n"; next; }
    It reads kinda nicely. "unless we can open the directory, yell"

    Some people might dislike that technique since the evalaution of the conditional has a side effect (that the directory is opened)...but I think it'd like it better than the right hand side of an inlined 'or' having one... ;)

    /\/\averick
    OmG! They killed tilly! You *bleep*!!

Re: or with a block
by kpo (Initiate) on Jun 01, 2002 at 06:55 UTC
    just thought id point out another obvious solution...
    opendir(DIR, "$path") or warn $!; yell(); sub yell() { #other code here... }