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:
I want this code to be like this:
How can I do it?
Can you send me a basic hello world example?
the directory structure is like this:
The helperFunctions dir will be like this:
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;
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;
How can I do it?
Can you send me a basic hello world example?
the directory structure is like this:
/dir1/yyy.pm
The helperFunctions dir will be like this:
/dir1/helperFunctions/lineNumbers.pm
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I believe you can use "use" also:
http://perldoc.perl.org/functions/use.html
http://perldoc.perl.org/functions/use.html
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;
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();
ASKER