Hi.

I recently wanted to load another version of a module from a module of the same name. i.e. I wanted to load "../ModX.pm" instead of "./ModX.pm" (changing the load path wasn't an option at the time).

I tried this (in ./ModX.pm):

BEGIN { delete $INC{'ModX.pm'}; use lib '../'; use ModX; }
but this just kept the loaded version (./ModX.pm) loaded. After trying a few things, I found this worked:
BEGIN { delete $INC{'ModX.pm'}; use lib '../'; require '../ModX'; # Yes, I know I haven't done import }
Which I found odd, because perldoc -f use says that use is exactly equivalent to: BEGIN { require Module; import Module LIST; } To some extent I was happy, but I was still curious.

Some more playing around and I reaslised my error (which is probably obvious to many, but not to some, hence this post).

use is exactly equivalent to the above, and the issue is the nested BEGIN blocks. The effective code being run (ignoring imports) is:

BEGIN { delete $INC{'ModX.pm'}; use lib '../'; BEGIN { require 'ModX.pm'; } }
and so...the inner BEGIN block executes before the contents of the enclosing block, so you get the effect of something like:
BEGIN { require 'ModX.pm'; delete $INC{'ModX.pm'}; use lib '../'; }
where the require does nothing (because we have not yet frobbed %INC).

I thought this interesting. My error was in thinking of 'compile time' versus 'run time'. Everything I was doing was at 'compile time' so I wasn't thinking in terms of that.

Does anyone have anything to offer regarding:

Thanks for reading :-)

In reply to BEGIN and compile-time by jbert

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.