Answers to Chapter 16 Exercises
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
execfunction 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.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
STDOUTandSTDERRto 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
diego? Why, it would go into ls.err, of course, since that’s whereSTDERRis going at that point. Thediefromchdirwould go there, too. But where would the message go if we can’t reopenSTDERRon the second line? It goes to the oldSTDERR. If reopening the three standard filehandles—STDIN,STDOUT, andSTDERR—fails, the old filehandle is still open.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, ...