wsly has asked for the wisdom of the Perl Monks concerning the following question:
But, my module B want to access the methods in module A. what's the right way for this purpose?use lib '/opt/lib'; use A; use B;
Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: modules relation question
by tobyink (Canon) on Jun 16, 2023 at 06:09 UTC | |
Without more information it's hard to say what is the best way to achieve this. Using names more specific than "A" and "B" might give us more clues about what you need. Inheritance is for object-oriented programming, where one class is logically a subclass of another class. For example, if you have "Animal" and "Bear" packages, it would make sense for "Bear" to inherit from "Animal".
If you're not using object-oriented programming, then you don't want inheritance. For example, if your modules are "AliceUtils" and "BobUtils" and Bob wants to use a few of Alice's utility functions in his code, then:
Often you don't want to fully-qualify sub names like BobUtils::save_file and would prefer to call them by just their unqualified sub name like save_file. If you want that, then you make the modules exporters. For this example, I'm going to use Exporter::Shiny to do that, because it's simple and I made it. There are many other ways to turn your module into an exporter though, including Exporter.pm which comes bundled with Perl.
(Generally speaking, if your module is written to be used as a class in object-oriented programming, it should not be an Exporter. Exporters are more for bundles of utility functions. And yes, I know there are exceptions to this rule.) | [reply] [d/l] [select] |
|
Re: modules relation question
by kcott (Archbishop) on Jun 16, 2023 at 06:07 UTC | |
G'day wsly, Welcome to the Monastery. [That's an unfortunate choice of example module names as B already exists and is a core module. I'm going to pretend you wrote X and Y. You may want to change that in your post; How do I change/delete my post? explains how to do this.] There's a number of ways to do this. Please tell us about the relationship between these two modules. Here's some possibilities: You may want to look at Exporter for the first of those relationships; or "perlootut - Object-Oriented Programming in Perl Tutorial" for the remainder. — Ken | [reply] [d/l] [select] |