Answers to Chapter 5 Exercises
Here’s one way to do it:
print reverse <>;
Well, that’s pretty simple! But it works because
printis looking for a list of strings to print, which it gets by callingreversein a list context. Andreverseis looking for a list of strings to reverse, which it gets by using the diamond operator in list context. So, the diamond returns a list of all of the lines from all of the files of the user’s choice. That list of lines is just what cat would print out. Nowreversereverses the list of lines, andprintprints them out.Here’s one way to do it:
print "Enter some lines, then press Ctrl-D:\n"; # or Ctrl-Z chomp(my @lines = <STDIN>); print "1234567890" x 7, "12345\n"; # ruler line to column 75 foreach (@lines) { printf "%20s\n", $_; }Here, we start by reading in and chomping all of the lines of text. Then we print the ruler line. Since that’s a debugging aid, we’d generally comment-out that line when the program is done. We could have typed
"1234567890"again and again, or even used copy-and-paste to make a ruler line as long as we needed, but we chose to do it this way because it’s kind of cool.Now, the
foreachloop iterates over the list of lines, printing each one with the%20sconversion. If you chose to do so, you could have created a format to print the list all at once, without the loop:my $format = "%20s\n" x @lines; printf $format, @lines;
It’s a common mistake to get 19-character columns. That happens when you say to yourself,[*] “Hey, why do we ...