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.


In reply to Re: variable import from package fails even though package apparently loads by ikegami
in thread variable import from package fails even though package apparently loads by spoonervt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.