home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

A.13. Answers to Chapter 14 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 hard-coded 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 re-open STDERR on the second line? It goes to the old STDERR. For the three standard filehandles, STDIN, STDOUT, and STDERR, if re-opening them 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, and the day of the week is the first part of the output of the date command, this is pretty simple. Just check the output of the date command to see if it starts with S. There are many harder ways to do this program, and we've seen most of them in our classes.

    If we had to use this in a real-world program, though, we'd probably use the pattern /^(Sat|Sun)/. It's a tiny bit less efficient, but that hardly matters; besides, it's so much easier for the maintenance programmer to understand.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.