[Appendix A] A.11 Chapter 12, Directory Access
Author: Randal L. Schwartz, Erik Olson & Tom Christiansen
Date: 1999-07-02T01:37:39Z

#

| Appendix A Exercise Answers |

## A.11 Chapter 12, Directory Access

1. Here's one way to do it:

       print "Where to? ";
       chomp($newdir = <STDIN>);
       chdir($newdir) || die "Cannot chdir to $newdir: $!";
       foreach (<*>) {
         print "$_\n";
       }

   The first two lines prompt for and read the name of the directory.

   The third line attempts to change the directory to the given name, aborting if this isn't possible.

   The `foreach` loop steps through a list. But what's the list? It's the glob in a list context, which expands to a list of all of the filenames that match the pattern (here, `*`).

2. Here's one way to do it, with a directory handle:

       print "Where to? ";
       chomp($newdir = <STDIN>);
       chdir($newdir) ||
         die "Cannot chdir to $newdir: $!";
       opendir(DOT,".") ||
         die "Cannot opendir . (serious dainbramage): $!";
       foreach (sort readdir(DOT)) {
           print "$_\n";
         }
       closedir(DOT);

   Just as with the previous program, we prompt and read a new directory. After we've `chdir`'ed there, we open the directory creating a directory handle named `DOT`. In the `foreach` loop, the list returned by `readdir` (in a list context) is sorted, then stepped through, assigning each element to `$_` in turn.

   And here's how to do it with a glob instead:

       print "Where to? ";
       chomp($newdir = <STDIN>);
       chdir($newdir) || die "Cannot chdir to $newdir: $!";
       foreach (sort <* .*>) {
           print "$_\n";
       }

   Yes, this solution is basically the other program from the previous exercise, but I've added a `sort` operator in front of the glob, and I also added `.*` to the glob to pick up the files that begin with dot. We need the `sort` because a file named `!fred` belongs before the dot files, and `barney` belongs after them. In addition, an easy glob pattern that can get them all in the proper sequence does not exist.

A.10 Chapter 11, Formats |  | A.12 Chapter 13, File and Directory Manipulation