4

I had 1 perl script in which we write couple of subroutines. Example:

# Try_1.pl

main();

sub main{
---
---
 check();
}

check {
--
--}

Now, i wrote another script Try_2.pl, in which i want to call check subroutine of perl script Try_1.pl.

4 Answers 4

7

It sounds like you want to create a module. Try_1.pm (Edit: note extension) should have the following form:

package Try_1;
use base 'Exporter';
our @EXPORT = qw(check);

sub check {
}

1;

And then Try_2.pl needs to get that code:

use Try_1 qw(check);

That what you're looking for?

Sign up to request clarification or add additional context in comments.

5 Comments

Also the file containing this package will need to be named Try_1.pm and placed in your @INC path.
further, since you use @EXPORT you do not need to explicitly import the function check in Try_2.pl, a simple use Try_1 will work. You may use @EXPORT_OK to require an explicit import.
@Joel Sure, you don't need to specify the function, but it's good practice to only import the functions you need. If you specify particular functions explicitly, it does not import anything else. It also tells you up at the top of your code just how much your global namespace is being polluted (since you're calling them out explicitly, it's arguably not being 'polluted' at all).
Is it possible to make variables global, across the main script and also the modules that you create? If so, how would it be done as I am having some trouble? thanks a lot
@perl-user That's a different question - you should search SE and then if you don't find the answer you should ask it as a question.
5

If you are not using modules (extension .pm) but instead use libraries (extension .pl):

require 'Try_1.pl';
check();

Make sure that both files Try_1.pl and Try_2.pl are in the same directory.

Comments

1

You may need this

test1.pl:

use Routines;
{    
    my $hello = "hello123";
    hello( $hello );    
    # ...
}

test2.pl:

package Routines;
sub hello 
{
    my $hello = shift;
    print "$hello\n";
}
1;

Comments

0

"run"'s answer tested work, but need to call like "Try_1::check()". Otherwise show error "Undefined subroutine &main::check()".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.