Multiple packages in one file

I was reading an interesting discussion on python-dev, and it made me think about the analogous situation in Perl. I've long been in the habit of putting each package into its own file, no matter what. Now I'm starting to consider combining related packages into one file, and only breaking things up along lines of reuse.

I initially thought there was consensus in Perl circles to have a single file per package, but on further reflection, I started to doubt myself. I don't actually have much confidence that this is true. I don't usually look at the file structure of distributions I use from CPAN. Maybe there is more combining than I realized. Any thoughts?


The Perl standard is that a package name matches a file name (with s{::}{/}g) and that each package name corresponds to a single file.

Of course, as with anything in Perl, it's a loose standard, but I think if you look at most modern Perl modules you'll find that they stick to this.

There are a couple exceptions I can think of ...

1. You're creating some sort of "internal use only" package that will only be used by one other package in your distro, so you stick it in the same module file.

2. You're monkey-patching some module outside of your distro.

In both cases, you should probably avoid exposing the package to the public at all, which means hiding it from CPAN indexing (package<newline>Foo::Bar and/or no_index in META.{yml,json}).

When putting multiple module in one file, you can no longer require that module, because it can't be found on the filesystem (require won't know it's already loaded). This also means you can't use it in combination with base or parent.

Leave a comment

About cbt

user-pic I like to write computer programs, for both fun and profit. I enjoy Perl the most, but plenty of other languages are good too.