Blob


1 #!/usr/bin/perl
3 #Extra credit exercise: write a subroutine, called &above_average, which takes a list of numbers and returns the ones 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:
5 use v5.10;
6 use warnings;
7 use strict;
8 use utf8;
10 sub total {
11 my $sum = 0;
12 foreach (@_) {
13 $sum += $_;
14 }
15 return $sum;
16 }
17 sub above_average {
18 my $average = total(@_) / scalar(@_);
19 my @ints;
20 foreach (@_) {
21 push @ints, $_ if $_ > $average;
22 }
23 return @ints;
24 }
26 my @fred = above_average(1..10);
27 print "\@fred is @fred\n";
28 print "(Should be 6 7 8 9 10)\n";
29 my @barney = above_average(100, 1..10);
30 print "\@barney is @barney\n";
31 print "(Should be just 100)\n";
33 #Write a subroutine named greet that welcomes the person you name by telling them the name of the last person it greeted:
35 sub greet {
36 state $lastperson;
37 if (!defined($lastperson)) {
38 print "Hi $_! You are the first one here!\n";
39 } else {
40 print "Hi $_! $lastperson is also here!\n";
41 }
42 $lastperson = $_;
43 }
45 greet("Fred");
46 greet("Barney");
48 #This sequence of statements should print:
50 #Hi Fred! You are the first one here!
51 #Hi Barney! Fred is also here!