Musa Yıldırım Musa Yıldırım - 7 months ago 12
Perl Question

How to add a library from another perl file?

I want to import a library into my perl script. Below is my attempt:

function.pl

#!/usr/bin/perl
package main;
use strict;
use warnings;
use 5.005;
use Term::ANSIColor qw(:constants);
use LWP::Simple;
use diagnostics;
use File::Spec;
use Getopt::Long;
use File::Basename;
use Cwd 'abs_path';

sub myfunction {
print RED, " Deleting...", RESET;
system("rm –f /file_location/*.");
print "deleted.\n";
}


I want to import function.pl in this new perl script.

#!/usr/bin/perl
package main;

myfunction;
myfunciton2;

Answer

If you just want a container for a number of utility subroutines then you should create a library module using Exporter

Name your package and your module file something other than main, which is the default package used by your main program. In the code below I have written module file Functions.pm which contains package Functions. The names must match

Functions.pm

package Functions;

use strict;
use warnings;

use Exporter 'import';
our @EXPORT_OK = qw/ my_function /;

use Term::ANSIColor qw(:constants); 


sub my_function {
    print RED, " Deleting...", RESET;
    system("rm –f /file_location/*.");
    print "deleted.\n";      
}

1;

program.pl

#!/usr/bin/perl    

use strict;
use warnings 'all';

use Functions qw/ my_function /;

my_function();