in reply to variable import from package fails even though package apparently loads

Three things need to match:


In your working version, you have

They match, so all's good.

This is what happens:

use w; loads w.pm, then checks if the w namespace provides a method named import. If it does, the method is called.

The module asks Exporter to provide this method and to export $var_in_w and sub_in_w when called (with no additional arguments). $var_in_w and sub_in_w are therefore exported.


In your broken version, you have

The package directive doesn't match the other two, so problems are to be expected.

This is what happens:

use A::w; loads A/w.pm, then checks if the A::w namespace provides a method named import. If it does, the method is called.

The A::w namespace doesn't provide an import method. Nothing exports $var_in_w and sub_in_w.


If the file is to remain at A/w.pm relative to the script's dir,

The choice of fix will come down to this question: Is the module named A::w (fix #1), or is it named w and happens to be in a directory named A (fix #2)?

For example, one might organize their project as follows:

This could be coded as follows:

scripts/script.pl
use FindBin qw( $RealBin ); use lib "$RealBin/../lib"; use Foo::Bar; ...
lib/Foo/Bar.pm
package Foo::Bar; ...

  1. $RealBin is the directory that contains the script. . is the current work directory, which has nothing to do with the directory that contains the script. If they happen to be the same, it's just a coincidence.

Update: Many tweaks to presentation.

Replies are listed 'Best First'.
Re^2: variable import from package fails even though package apparently loads
by spoonervt (Initiate) on Jan 06, 2025 at 19:20 UTC
    Thank you for the explanation. I somehow missed the fact that I needed to replicate the directory hierarchy path in the package declaration.