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 16 Exercises

  1. Here’s one way to do it:

    chdir "/" or die "Can't chdir to root directory: $!";
    exec "ls", "-l" or die "Can't exec ls: $!";

    The first line changes the current working directory to the root directory, as our particular hardcoded directory. The second line uses the multiple-argument exec function to send the result to standard output. We could have used the single-argument form just as well, but it doesn’t hurt to do it this way.

  2. Here’s one way to do it:

    open STDOUT, ">ls.out" or die "Can't write to ls.out: $!";
    open STDERR, ">ls.err" or die "Can't write to ls.err: $!";
    chdir "/" or die "Can't chdir to root directory: $!";
    exec "ls", "-l" or die "Can't exec ls: $!";

    The first and second lines reopen STDOUT and STDERR to a file in the current directory (before we change directories). Then, after the directory change, the directory listing command executes, sending the data back to the files opened in the original directory.

    Where would the message from the last die go? Why, it would go into ls.err, of course, since that’s where STDERR is going at that point. The die from chdir would go there, too. But where would the message go if we can’t reopen STDERR on the second line? It goes to the old STDERR. If reopening the three standard filehandles—STDIN, STDOUT, and STDERR—fails, the old filehandle is still open.

  3. Here’s one way to do it:

    if (`date` =~ /^S/) {
      print "go play!\n";
    } else {
      print "get to work!\n";
    }

    Well, since both Saturday and Sunday start with an S, ...

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