odd problem with open()

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi, I'm running perl 5.6.0 on Mac OS X (darwin) and have a program with
the following code:

  sub do_dir {
       my $dir = shift;
        opendir(DIR, $dir) or die "Can't open directory '$dir' $!";

        while ($file = readdir(DIR)) {
                next if $file =~ /^\.\.?$/;
                next if -l "$dir/$file";

                if (-d "$dir/$file") {
                } elsif (-f "$dir/$file") {
                         open(FILE, "$dir/$file") or die "Can't open
'$dir/$file': $!";


i.e. it's recursing through the filesystem, skipping symbolic links
(because there are entries linked back to a parent directory (!)) and
skipping '.' and '..' of course.

This works fine except when it comes across a filename like


i.e. where the last character is a CR, when the program dies.

Now, I don't know why the odd file has a CR in it's name, but why
doesn't open() work anyway?

At present I've resorted to

#               chop $file if $file =~/\r$/;
                chop $file if substr($file, -1, 1) eq "\r";

(substr seems to be slightly quicker here)



Re: odd problem with open()

Colin Howarth wrote:

Quoted text here. Click to load it

It is not a good idea to call readdir() in scalar context when doing
recursion.  An older version of perl would lose its place in the
parent readir() when the subdirectory readdir() started.

If you're going to re-invent the wheel that has already been solved
via File::Find, be sure to use lexical file handles and dir handles,
not global ones.

Re: odd problem with open()

Joe Smith wrote:
Quoted text here. Click to load it

This is a work arond I once imployed in a some what similar situation
(as far as using a file handle of the same name multiple time from the
result of recursion) :

sub do_dir {
       # makes sure DIR from resursive calls to do_dir() don't clash.
       local *DIR; # localize file handle.

       while ($file = readdir(DIR)) {
               if (-d "$dir/$file") {

Quoted text here. Click to load it

Good mudule. Just FYI, for the last part of the sentance, my addition to
the OP's code applies as well :-)

Site Timeline