Search code examples
perlmoduleexportsubroutine

How to import subroutines from modules in perl


I am novice in perl. I have this sample code.

#! /usr/bin/perl
# Calcu.pm

package Calc;

sub add {
    ( $one , $two ) = @_;
    $total = $one + $two;
    return $total;
    }

1;

&

#! /usr/bin/perl
# add.pl

use Calcu;

print Calcu::add(50, 60);

script add.pl is running fine. but I want to call the add method without mentioning its module name. I googled & added below lines in my Calcu.pm

use Exporter;

@ISA = (Exporter);
@EXPORT = qw (add);

& replace print Calcu::add(50, 60); with print add(50, 60); in add.pl but it is still giving me the below error.

Undefined subroutine &main::add called at add.pl 

Is there any way possible so that I can directly call add subroutine in my ad.pl?


Solution

  • Change package Calc; to package Calcu; in Calcu.pm

    The mismatch in package names is what is giving you trouble.

    Have a read through perldoc Exporter for the gory details.

    Have a look at perldoc perlootut for an overview of different ways in perl to create objects.