Learning Perl

Learning PerlSearch this book
Previous: A.10 Chapter 11, FormatsAppendix A
Exercise Answers
Next: A.12 Chapter 13, File and Directory Manipulation
 

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 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 like the previous program, we prompt and read a new directory. Once 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, and 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, it's basically the other program from the previous exercise, but I've added a sort operator in front of the glob and 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, but barney belongs after them, and there isn't an easy shell glob that can get them all in the proper sequence.


Previous: A.10 Chapter 11, FormatsLearning PerlNext: A.12 Chapter 13, File and Directory Manipulation
A.10 Chapter 11, FormatsBook IndexA.12 Chapter 13, File and Directory Manipulation