Appendix A. Answers to Exercises
This appendix contains the answers to the exercises presented throughout the book.
Answers for Chapter 2
Exercise 1
Here’s one way to do it. The command-line arguments show up in
the special array @ARGV, so we use
that for our input list. The file test operator -s works on $_ by default, and that’s just the current
element that grep tests. All of the
files with a byte -size smaller than 1,000 bytes end up in @smaller_than_1000. That array becomes the
input for the map, which takes each
element and returns it with spaces tacked on the front and a newline
on the end.
#!/usr/bin/perl
my @smaller_than_1000 = grep { -s < 1000 } @ARGV;
print map { " $_\n" } @smaller_than_1000;Typically we’ll do that without the intermediate array, though.
print map { " $_\n" } grep { -s < 1000 } @ARGV;Exercise 2
We chose to use our home directory as the hardcoded directory.
When we call chdir without an
argument, it goes to our home directory (so this is one of the few
places where Perl doesn’t use $_ as
the default).
After that, an infinite while
loop keeps our code running, at least until we can’t satisfy the
condition to last that breaks us
out of the loop. Look at the condition carefully: we don’t just test
for truth. What would happen if we wanted to find all the files with a
0 in them? We look for defined
values with a nonzero length, so undef (end of input) and the empty string
(simply hitting enter) stop the loop.
Once we have our regular expression, we do that same thing ...