Документация
HTML CSS PHP PERL другое

Section A.13.  Answers to Chapter 14 Exercises

 
Previous
Table of Contents
Next

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 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, 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. 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 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";
        }
    

    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 fairly simple. 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, we'd probably use the pattern /^(Sat|Sun)/. It's a tiny bit less efficient, but that hardly matters; besides, the maintenance programmer can understand it more easily.

    Previous
    Table of Contents
    Next
    © 2000- NIV