Contents:
Moving Around the Directory Tree
Globbing
Directory Handles
Opening and Closing a Directory Handle
Reading a Directory Handle
Exercises
By now, you're probably familiar with the notion of the current directory and using the
cd
command at the command prompt. If you were programming in C, you'd be invoking the
chdir ()
call to change the current directory of a program; this name is also used by Perl.
The
chdir
function in Perl takes a single argument - an expression evaluating to a directory name to which the current directory will be set. As with most other system calls,
chdir
returns true if you've successfully changed to the requested directory and false if you couldn't. Here's an example:
chdir("c:/temp") || die "cannot cd to c:/temp ($!)";
The parentheses are optional, so you can also get away with stuff like:
print "where do you want to go? "; chomp($where = <STDIN>); if (chdir $where) { # we got there } else { # we didn ' t get there }
You can't find out where you are without launching a cc command (something like cmd /c cd , or some moral equivalent[ 1 ]). We'll learn about launching commands in Chapter 14, Process Management .
[1] Other solutions are using the
getcwd
function out of theCwd
module or theWin32::GetCwd
function.
Every process[ 2 ] has its own current directory. When a new process is launched, it inherits its parent's current directory, but that's the end of the connection. If your Perl program changes its directory, the change won't affect the parent program that launched the Perl process. Likewise, the processes that the Perl program creates cannot affect that Perl program's current directory. The current directories for these new processes are inherited from the Perl program's current directory.
[2] A process is the technical jargon for an executing program.
The
chdir
function without a parameter defaults to taking you to your home directory, in imitation of a typical UNIX shell's
cd
command. The
cd
command in Windows NT does not normally work this way. In order to guess your home directory, Perl will check to see whether the
HOME
or
LOGDIR
environment variables are defined.