Answers to Chapter 12 Exercises

  1. Here’s one way to do it, with a glob:

        print "Which directory? (Default is your home directory) ";
        chomp(my $dir = <STDIN>);
        if ($dir =~ /^\s*$/) {         # A blank line
          chdir or die "Can't chdir to your home directory: $!";
        } else {
          chdir $dir or die "Can't chdir to '$dir': $!";
        }
        my @files = <*>;
        foreach (@files) {
          print "$_\n";
        }

    First, we show a prompt and read the desired directory, chomping it as needed. (Without a chomp, we’d be heading for a directory that ends in a newline, which is legal in Unix and therefore cannot be presumed to be extraneous by the chdir function.)

    If the directory name is nonempty, we’ll change to that directory, aborting on a failure. If empty, the home directory is selected instead.

    Finally, a glob on “star” pulls up all the names in the (new) working directory, automatically sorted to alphabetical order, and the names are printed one at a time.

  2. Here’s one way to do it:

        print "Which directory? (Default is your home directory) ";
        chomp(my $dir = <STDIN>);
        if ($dir =~ /^\s*$/) {         # A blank line
          chdir or die "Can't chdir to your home directory:
        $!";
        } else {
          chdir $dir or die "Can't chdir to '$dir': $!";
        }
        my @files = <.* *>;       ## now includes .*
        foreach (sort @files) {   ## now sorts
          print "$_\n";
        }

    Two differences from previous one: first, the glob now includes “dot star,” which matches all the names that do begin with a dot. Second, we must sort the resulting list because some of the names that begin with a dot must be interleaved appropriately ...

Get Learning Perl, Fourth 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.