Modules


We could have placed the package keyword and the code in the main script or we can put several packages in the same external file but the best approach is to put every package in a separate file having the same name as the package itself (case sensitive) and .pm as file extension.

Then we call it a Perl Module.


examples/modules/module.pl
#!/usr/bin/perl
use strict;
use warnings;

use lib 'examples/modules';

require Calc;

print Calc::add(3, 4), "\n";

examples/modules/Calc.pm
package Calc;
use strict;
use warnings;

my $base = 10;

sub add {
    validate_parameters(@_);

    my $total = 0;
    $total += $_ for (@_);
    return $total;
}

sub multiply {
}

sub validate_parameters {
    die 'Not all of them are numbers'
        if  grep {/\D/} @_;
    return 1;
}



1;