porton
porton

Reputation: 5803

Multiple Perl packages in one file?

Please enumerate all reasons supporting the following saying: "Each Perl package should be placed into a separate file (no several packages in one file)".

For example, I have a code like this:

{
package Classes::City;
# ...
}
{
package Classes::Cities; # for lists of multiple cities
# ...
}

Should I refactor this code into two separate .pm files? (Consider this question as an example of the above question, not as an additional opinion-based question. I want just the list arguments, not an opinion-based answer.)

Upvotes: 3

Views: 838

Answers (2)

Erik Bennett
Erik Bennett

Reputation: 1099

A single answer is that this is not the intended usage model, and the compiler/interpreter will fight with you in ways that aren't always obvious.

Your example is very similar to something I try to do: create a class, and then a container class for the original class within the same file.

I've found that 8 times out of 10, I can get it to work without too much pain.

If the original class contains BEGIN blocks for (say) accessors, it's not always clear that they get executed before you try to use the accessors in your container class. I'm sure there are combinations of gyrations which will make this happen, but at that point, it seems cleaner to just use the 1 package/file model.

Even forcing a BEGIN { import class;} from within the container class won't always be enough to get things to run in the necessary order.

Upvotes: 0

simbabque
simbabque

Reputation: 54323

The main reason is that Perl loads modules for you automatically when you use or require them with package names. It does so by converting the package name to path in your file system and checking each of your @INC directories for that file.

use Classes::City;
# will be converted to on Linux:
Classes/City.pm

If you have both Classes::City and Classes::Cities in one file, you cannot load ::Cities without loading City because the file Classes/Cities.pm does not exist anywhere in your @INC.

use Classes::City
# blows up

You now need to keep track which packages are in what file. That makes your life harder.

Upvotes: 4

Related Questions