[sf-perl] Exporter and subroutine circular dependencies between modules

David Christensen dpchrist at holgerdanske.com
Sun Jun 5 19:05:24 PDT 2022


On 3/13/22 13:13, David Christensen wrote:
 > I have been wrestling with the Exporter module and subroutine circular
 > dependencies between modules for a number of years.

https://www.mail-archive.com/module-authors@perl.org/msg10914.html


We revisited this topic at a San Francisco Perl Mongers meeting today:

https://mail.pm.org/pipermail/sanfrancisco-pm/2022-June/004851.html


I showed the following snippet of code that demonstrates the solution I 
am currently using:

      6	package Dpchrist::Lib5::Test;
      7	
      8	
      9	use strict;
     10	use warnings;
     11	use threads;
     12	use threads::shared;
     13	
     14	our @EXPORT_OK;
     15	
     16	BEGIN {
     17	    @EXPORT_OK =	qw(
     18				    is_poly
     19				);
     20	}
     21	
     22	use parent		qw(
     23				    Exporter
     24				    Test::Builder::Module
     25				);


The key points are:

* Put the Exporter-related statements (lines 14-25) near the top of the 
module, before other code.

* Statement ordering is important:

   * First -- declare @EXPORT_OK, but do not define/ initialize it (line 
14).

   * Next -- define/ initialize @EXPORT_OK in a BEGIN block (lines 16-20).

   * Finally -- 'use parent' to inherit from Exporter (lines 22, 23, and 
25).

* The above module also happens to inherit from Test::Builder::Module. 
My other modules do not need or have line 24.

* As I develop code and introduce bugs, I frequently see warnings to the 
effect "subroutine redefined" when there is a circular loop between 
modules.  Once I fix the bugs, those warnings go away.


Without understanding the "how" and "why" of perl(1), Exporter, "compile 
time", "run time", "require", "use", "parent", "import", etc. -- of the 
several solutions myself and others have tried over time, this one seems 
to work the best for me.


David


More information about the SanFrancisco-pm mailing list