home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Learning Perl

Learning PerlSearch this book
Previous: 11.7 Exercises Chapter 12 Next: 12.2 Globbing
 

12. Directory Access

12.1 Moving Around the Directory Tree

By now, you're probably familiar with the notion of the current directory and using the shell's cd command. In systems programming, you'd be invoking the chdir system call to change the current directory of a process, and this is the name used by Perl as well.

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 when you've successfully changed to the requested directory and false if you couldn't. Here's an example:

chdir("/etc") || die "cannot cd to /etc ($!)";

The parentheses are optional, so you can also get away with stuff like this:

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 pwd command.[ 1 ] We'll learn about launching commands in Chapter 14, Process Management .

[1] Or using the getcwd() function out of the Cwd module.

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, it won't affect the parent shell (or whatever) 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] Well, in UNIX and most other modern operating systems.

The chdir function without a parameter defaults to taking you to your home directory, much like the shell's cd command.