A.11. Chapter 12

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

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.