O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required