I originally learned what Perl I know back in the 90's, and tended then (and still do, sometimes) to put common subroutines into a 'standard.pl' library which I would 'require' where needed. I know that most people bundle such routines into a module these days, and I understand some of the reasons for this. I was burned today and wondered if someone could explain to me (using small words) just why.

Suppose I have the following modules:

package A; use B; require 'standard.pl'; sub new { # [snip] bless ($self, $class); do_something(); # subroutine in standard.pl return $self; }
package B; require 'standard.pl'; sub new { # [snip] bless ($self, $class); do_something(); # subroutine in standard.pl return $self; }
# standard.pl # [snip] sub do_something { print "Howdy.\n"; } 1;

When I tried to run a script that used module A, I got an error message like this:

Undefined subroutine A::do_something called at A.pm line X.

I eventually realized that module B was requiring the same standard.pl library and changed the code in A to no longer require the standard.pl libary and the invocation of the do_something() routine from:

do_something();

to:

B::do_something();

... which worked. It made me feel a little deceptive, referring to a common subroutine in standard.pl as though it was part of module B, though. Why couldn't module A 'see' that do_something() subroutine in its own namespace, since I explicitly 'require'-d it in both modules?

Maybe the moral of the story is that I shouldn't be mixing packages and libraries, but I would like to understand this better in any case.


In reply to Burned by 'require'? by ptum

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.