Musa Yıldırım
Musa Yıldırım

Reputation: 1

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;

Upvotes: 0

Views: 530

Answers (2)

Sebastian
Sebastian

Reputation: 2550

Remove that package main; - it's not needed.

Best practice way (but not the easiest one):

Create a new directory MyApp (replace by some unique name for your application) and place a file Global.pm into this directory:

package MyApp::Global; # Same name as Directory/File.pm!
use strict;
use warnings;

use Exporter;
use Term::ANSIColor qw(:constants);

our @ISA       = ('Exporter');
our @EXPORT_OK = qw(myfunction);

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

1; # Important!

Insert into both files (function.pl and the newone.pl) right after the use lines:

use MyApp::Global qw(myfunction);

Basic way (PHP-like: Easier, but not "Best Practice"):

Create a file global.pl (or any other name):

use strict;
use warnings;

use Term::ANSIColor qw(:constants);

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

1; # Important!

Insert into both files (function.pl and the newone.pl) right after the use lines:

require 'global.pl';

See also:

Upvotes: 4

Borodin
Borodin

Reputation: 126762

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();

Upvotes: 1

Related Questions