3

I have two perl scripts. Both have no "package" keyword or anything. One has a sub (and plus some free floating code too) that I want to use in another script, without running the free floating code in the process.

A.pl
sub my_sub {
    # do something
}

# do something else
my_sub();
# do something else

B.pl
require A.pl; # but load only the subs, don't run anything
my_sub();

Is this possible without having to separate out the sub in a separate .pm file and then loading it?

2

1 Answer 1

11

require will run the code. So then you need A.pl to recognise the difference between being loaded and being called on the command line. I think it can be done, but you're kind of missing the point.

Instead, I highly recommend reversing everything. Instead of having mammoth pl scripts, and no pm modules, reverse it and have tiny pl files whose sole function is to load module(s) and call into the function that encapsulates the functionality there. And then it's trivial to add new modules to hold shared form or functionality.

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

3 Comments

I agree wholeheartedly. But I am inheriting this code from somewhere. I usually code in Python (which has a nifty main attribute to recognize if a module is being imported or being run standalone). Thought there would be something like this in perl too.
@shikhanshu There is: caller. See the question I linked under your question. But Tanktalus is right: you should work to modularize your code instead.
@shikhanshu It's called "refactoring" and will greatly simplify your life over the medium and long terms. And often has simplified my life over the short term as well.

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.