Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page