Building a Module

To understand how a module is put together, let's walk through a simple example: a small statistics library. This will re-use functions from the end of Hour 8, abbreviated for space. The sample module, which we're going to call TYPStats, is shown in Listing 17.1.

Listing 17.1. Statistics Module
1: #!/usr/bin/perl -w
2: use strict;
3: package TYPStats;
4: 
5: sub mean {
6:        my(@data) = @_;
7:        my $sum;
8:        $sum += $_ foreach(@data);
9:        return @data ? ($sum / @data) : 0;
10: }
11: sub median {
12:       my(@data)=sort { $a <=> $b} @_;
13:       if (scalar(@data) % 2) {
14:               return($data[@data / 2]);
15:       }
16:       return(mean($data[@data / 2], 
17:            $data[@data / 2 - 1]));
18: }
19: 1;

This should be saved into a file called TYPStats.pm in the same ...

Get SAMS Teach Yourself Perl in 24 Hours THIRD EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.