Link to home
Start Free TrialLog in
Avatar of Tolgar
Tolgar

asked on

How to create a seperate helper function in Perl?

Hi,
I have a few Perl packages. In these packages, there is a piece of code that I repeat every time. Therefore, I would like to create a separate function (a separate function in a helperFunctions directory) and when I need that piece of code, I will call this function with certain inputs and return the output to the caller.

Example:
package xxx::yyy;
use strict;
use warnings;

sub yyy{

some code-1

some repetitve code-1
some repetitve code-2
some repetitve code-3
some repetitve code-4
some repetitve code-5

some code-2

}
1;

Open in new window


I want this code to be like this:
package xxx::yyy;
use strict;
use warnings;

sub yyy{

some code-1

call helperFunction lineNumbers.pm here and return the output

some code-2

}
1;

Open in new window


How can I do it?

Can you send me a basic hello world example?

the directory structure is like this:

/dir1/yyy.pm

Open in new window


The helperFunctions dir will be like this:

/dir1/helperFunctions/lineNumbers.pm

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of whosbetterthanme
whosbetterthanme
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tolgar
Tolgar

ASKER

@whosbetterthanme: Is "require" the only way to do this?
Avatar of wilcoxon
Using "use" is more standard.  Generally, you'll write a module something like:
package MyFunctions;
require Exporter;
use base qw(Exporter);
@EXPORT = qw(helperFunction1);
sub helperFunction1 {
...
}
1;

Open in new window

And then your program will have something like:
use lib 'some-dir'; # only needed if MyFunctions is not in somewhere pointed to by @INC
use MyFunctions;
helperFunction1();

Open in new window