Previous Table of Contents Next



I'm having problems with the following program. No files are read in, even though they're in the directory!

opendir(DIRHANDLE, "/mydir") || die;

@files=<DIRHANDLE> ;



Whoops! The problem is in the second line. DIRHANDLE is a directory handle, not a filehandle. You cannot read directory handles with the angle operators (<>). The correct way to read the directory is @files=readdir DIRHANDLE.


Why doesn't glob("*.*") match all the files in a directory?


Because "*.*" matches only filenames with a dot in them. To match all the files in a directory, use glob("*"). The glob function's patterns are designed to be portable across many operating systems and thus do not behave the same as the *.* pattern in DOS.


I modified the mygrep exercise to search subdirectories by using opendir and some more loops, but it seems to have bugs.


In short: Don't Do That. Descending a directory tree is an old problem, it's not particularly easy, it's been solved many times before, and you don't need to do it for yourself. (Doing all that work on a problem that's already been solved is called "reinventing the wheel.") If you're doing it only for fun, that's wonderful, but don't spend too much time on it. Hold on until Hour 15, where you'll learn to use the File::Find module instead. It's a lot simpler to useand, more importantly, it's debugged.


The program in Listing 10.3 gives an error if I try to change *.bat to *.tmp. Why?


The program wasn't expecting you to type *.bat as a pattern to look for. *.bat isn't valid to have in a regular expression* must follow some other character. If you had entered \*\.bat, the program would have accepted the input just finealthough it might not have worked as expected because filenames hardly ever have a literal * in them.

To fix this error, either give the program the input it expects (simple strings) or change line 19 to read s/\Q$oldpat/$newpat/ so that "special characters" are disabled in the regular expression patterns.

    Previous Table of Contents Next
    © 2000- NIV