PERL Exercises

  1. Write a program that computes the circumference of a circle with a radius of 12.5. Circumference is 2π times the radius (approximately 2 times 3.141592654). The answer you get should be about 78.5.
  2. Modify the program from the previous exercise to prompt for and accept a radius from the person running the program. So, if the user enters 12.5 for the radius, she should get the same number as in the previous exercise.
  3. Write a program that reads a list of strings on separate lines until end-of-input and prints out the list in reverse order. If the input comes from the keyboard, you'll probably need to signal the end of the input by pressing Control-D on Unix, or Control-Z on Windows.
  4. Write a subroutine, named total, that returns the total of a list of numbers. (Hint: the subroutine should not perform any I/O; it should simply process its parameters and return a value to its caller.) Try it out in this sample program, which merely exercises the subroutine to see that it works. The first group of numbers should add up to 25.

    my @fred = qw{ 1 3 5 7 9 };
    my $fred_total = total(@fred);
    print "The total of \@fred is $fred_total.\n";
    print "Enter some numbers on separate lines: ";
    my $user_total = total(<STDIN>);
    print "The total of those numbers is $user_total.\n";

  5. Using the subroutine from the previous problem, make a program to calculate the sum of the numbers from 1 to 1000.
  6. Write a subroutine, called &above_average, that takes a list of numbers and returns the ones that are above the average (mean). (Hint: make another subroutine that calculates the average by dividing the total by the number of items.) Try your subroutine in this test program.

    my @fred = above_average(1..10);
    print "\@fred is @fred\n";
    print "(Should be 6 7 8 9 10)\n";
    my @barney = above_average(100, 1..10);
    print "\@barney is @barney\n";
    print "(Should be just 100)\n";

  7. Write a program that acts like cat, but reverses the order of the output lines. (Some systems have a utility like this named tac.) If you run yours as ./tac fred barney betty, the output should be all of file betty from last line to first, then barney and then fred, also from last line to first. (Be sure to use the ./ in your program's invocation if you call it tac so that you don't get the system's utility instead!)