Ïðèãëàøàåì ïîñåòèòü
Áàëüìîíò (balmont.lit-info.ru)

Q&A

Previous Table of Contents Next

Q&A

Q1:

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> ;

closedir(DIRHANDLE);


A1:

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.

Q2:

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

A2:

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.

Q3:

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

A3:

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 use—and, more importantly, it's debugged.

Q4:

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

A4:

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 fine—although 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