Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
For various portability reasons, I need to include a couple of custom packages in the same file as my application.

I have no problem wrapping each package in a BEGIN block and accessing methods the usual way. I can also export subroutines using exporter/import. However, I can't seem to export global variables. My code uses the following paradigm:
use strict; use warnings; MyPackage->import; #My main code $globalVar=1; myfunction(); #===================== BEGIN{ package MyPackage; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(globalVar myfunction); our $globalVar; sub myfunction {} #Rest of package code... }
Running, yields the error 'symbol "$globalVar" requires explicit package name'

When I dump the namespace for %main::, I get:
$VAR79 = 'globalVar'; $VAR80 = *::globalVar;
So, $globalVar seems to be in the namespace, I just can't seem to be able to use it (unless of course I explicitly address it using its originating namespace location as $MyPackage::globalVar)

If I put the package in a separate file and include it using 'use MyPackage', I get the same listing in the %main:: namespace as above but I am then able to access the global error directly without error.

Any ideas what is causing $globalVar not to be recognized when the package is in the same file as main?

In reply to Importing variables (not functions) from in-file packages by puterboy

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2023-06-06 22:41 GMT
Find Nodes?
    Voting Booth?
    How often do you go to conferences?

    Results (29 votes). Check out past polls.