Learning Perl: Missing Answers from Appendix A

(This goes in Appendix A, under Chapter 6, exercise 2, the current 2
and 3 should be 3 and 4)

2. Here's one way to do it:

@ARGV = reverse @ARGV;
print reverse < >;

The first line just takes any filename arguments and reverses
them. That way if the user called this script with command line
arguments "camel llama alpaca", @ARGV would then contain "alpaca llama
camel" instead. The second line reads in all the lines in all the
files in @ARGV, flips them end on end, and prints them. If no
arguments were passed to the program, then as before, <> works on
STDIN instead.

Here is the answer to exercise 2 from Chapter 9:

2. Here's one way to do it:

{
  print "Enter a number (999 to quit): ";
  chomp($n = );
  last if $n == 999;
  $sum += $n;
  redo;
}

print "the sum is $sum\n";

We're using a naked block with a redo and a last to get things done
this time. Start by printing the prompt and grabbing the number. If
it's 999, exit the block with last and print out the sum on exit.
Otherwise, we add to our running total and use redo to execute the
block again.


(anchor to local index page)

O'Reilly Home | Catalog | Customer Service | About O'Reilly | Contact Us | Index