Is there a way to encapsulate common Perl functions in my own scripts?

I support several Perl scripts that have the same code blocks for different functions. Every time a code block is updated, I have to go through each script and manually make changes.

Is there a way to encapsulate common functions in my own scripts and call them?

+3
source share
5 answers

There are other ways, but they all have serious problems. Modules are the way to go and they don't have to be very complex. Here is the basic template:

package Mod;

use strict;
use warnings;

use Exporter 'import';

#list of functions/package variables to automatically export
our @EXPORT = qw(
    always_exported   
); 

#list of functions/package variables to export on request
our @EXPORT_OK = qw(
    exported_on_request
    also_exported_on_request
);

sub always_exported { print "Hi\n" }

sub exported_on_request { print "Hello\n" }

sub also_exported_on_request { print "hello world\n" }

1; #this 1; is required, see perldoc perlmod for details

Create a directory, for example /home/user/perllib. Put this code in a file with a name Mod.pmin this directory. You can use the module as follows:

#!/usr/bin/perl

use strict;
use warnings;

#this line tells Perl where your custom modules are
use lib '/home/user/perllib';

use Mod qw/exported_on_request/;

always_exported();
exported_on_request();

, . , , . :: (, File::Find), /home/user/perllib. :: a /, My::Neat::Module /home/user/perllib/My/Neat/Module.pm. perldoc perlmod Exporter perldoc Exporter

+6
+12
+2

, .

do. , "mysub.pl"

do 'mysub.pl';

, .

0

require "some_lib_file.pl";

where you put all your common functions and call them from other scripts that will contain the line above.

For example:

146$ cat tools.pl
# this is a common function we are going to call from other scripts
sub util()
{
    my $v = shift;
    return "$v\n";
}
1; # note this 1; the 'required' script needs to end with a true value

147$ cat test.pl
#!/bin/perl5.8 -w
require 'tools.pl';
print "starting $0\n";
print util("asdfasfdas");
exit(0);

148$ cat test2.pl
#!/bin/perl5.8 -w
require "tools.pl";
print "starting $0\n";
print util(1);
exit(0);

Then execution test.pland test2.pllead to the following results:

149$ test.pl
starting test.pl
asdfasfdas

150$ test2.pl
starting test2.pl
1
0
source

Source: https://habr.com/ru/post/1716841/


All Articles