Blame


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