Answer to Chapter 14 Exercise

A.13 Answers to Chapter 14 Exercises

1.       Here's one way to do it:

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

3.       Here's one way to do it:

4.          open STDOUT, ">ls.out" or die "Can't write to ls.out: $!";
5.          open STDERR, ">ls.err" or die "Can't write to ls.err: $!";
6.          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.

7.       Here's one way to do it:

8.          if (`date` =~ /^S/) {
9.           print "go play!\n";
10.     } else {
11.      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.

 



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2001
Pages: 205

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net