in reply to constants in multiple libraries

It may just be my own personal prejudice, but I perfer not to ever require a .pl file. Whenever I move code out of the main script, I put it in a module (.pm) and use it.

Another standard practice I have found helpfull is to always start a module with a package declaration, and simply export anything that may be needed in the client code. I have actually run into problems with modules that do not have a package declaration. See the blow example:

#File Foo.pm sub make_foo { # do stuff } #File Bar.pm package Bar; use Foo; sub make_bar { &make_foo(); # It is defined here. # do stuff } #File myScript.pl #!/usr/local/bin/perl -w use strict; use Bar; use Foo; &make_foo(); # Undefined subroutine!

Becuase Bar.pm was included before Foo.pm, Foo.pm was compiled into the Bar:: namespace and now &main::make_foo(); is an undefined subroutine. Not good.

May the Force be with you

Replies are listed 'Best First'.
Re^2: constants in multiple libraries
by shemp (Deacon) on Sep 17, 2004 at 20:58 UTC
    Others may disagree with me on this, but for your example package Bar, id do the following instead:
    #File Bar.pm use Foo; package Bar; sub make_bar { main::make_foo(); # It is defined here. # do stuff }
    Because then, Foo is not part of Bar::, but part of main::, which is probably what you really want. I say this because it sounds like you want package Foo to be able to be used independently of Bar, so it shouldnt ever be tied strictly to Bar, because once it is, thats the only place it'll get put...unless you do some serious hand-waving.

      I have seen this approach taken before, so there are certainly people out there who will agree with you. However, the point I was trying to make is that Foo.pm should be a package of its own. If Foo.pm were package Foo; and exported &make_foo, then both Bar and main would have access to it without needing to fully qualify the package name.

      I feel that is is "sloppy" coding to refer to anything in the main namespace from inside an included package, because it violates encapsulation. When a package depends on methods or variables being defined in its client’s namespace, it becomes more difficult to accommodate. Explicitly referring to main from within a package is even worse because you might not be making assumptions about you're clients namespace, but rather your client's client's client's namespace. Such assumptions will make a code base unstable, and less extensible.

      May the Force be with you