Answers to Chapter 13 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 simple prompt and read the desired directory, chomping it as needed. (Without a chomp, we’d be trying to head for a directory that ends in a newline—legal in Unix, and therefore cannot be presumed to simply be extraneous by the chdir function.)

    Then, 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 in alphabetical order, and they’re 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 the previous one: first, the glob now includes “dot star”, which matches all the names that do begin with a dot. And second, we now must sort the resulting list because some of the names that begin with a dot ...

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