Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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.

use strict;
use warnings;

use lib 'examples/modules';

require Calc;

print Calc::add(3, 4), "\n";
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;

  • How did perl find the file Calc.pm ?
  • How could we use add() without the Calc:: ?
  • Why did we write “require” instead of “use”?