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

Dear Monks, I tried to open files in a folder. I use these two lines of code:
opendir (PRODIR, "D:/perldatabase/$folder[$II]") || die ("Unable to open directory");
So when it came to a file that can not be opened, my perl program just stoped. I wonder how to jump to the next file if one can not be opened? I am quite new at perl. Thank you for helping me. Yelenna

Replies are listed 'Best First'.
Re: How to jump to open the next file in the same folder?
by iburrell (Chaplain) on Oct 17, 2002 at 01:40 UTC
    If you are processing the elements in a list, use "next" to skip the rest of the loop and go to the next iteration. Just like the "continue" statement in C. You should be able to do (if you don't care about the reason):
    opendir() or next;
    Also, you should be clear that opendir opens a directory to read the list of files with readdir. You should check if the file is a directory before trying to open it. You can even use "next" to short-circuit the loop.
    next unless -d $file;
    BTW, it is an idiom in Perl to loop through a list with foreach instead of incrementing a counter ($II) like in C/Java. It is faster and makes the control clearer.
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: How to jump to open the next file in the same folder?
by samurai (Monk) on Oct 17, 2002 at 04:02 UTC
    Ok, so it's overkill, but I can't let one of these go by without mentioning one of my fave modules:

    use DirHandle; my $dh = new DirHandle("/path/to/dir") or die "Can't open /path/to/dir: $!"; while (my $entry = $dh->read()) { # here you can do either open FILE, "/path/to/dir/$entry" or next; # or like so -r "/path/to/dir/$entry" or next; # now, on to that file! <!-- your code here --> } $dh->close();

    --
    perl: code of the samurai