Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Exercises

See Appendix A for answers to the following exercises:

  1. [12] 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";
  2. [5] Using the subroutine from the previous problem, make a program to calculate the sum of the numbers from 1 to 1000.

  3. [18] Extra credit exercise: 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";
  4. [10] Write a subroutine, named greet, that welcomes the person you name by telling them the name of the last person it greeted:

    greet( "Fred" );
    greet( "Barney" );

    This sequence of statements should print:

    Hi Fred! You are the first one ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page