in reply to Using a module more than once

so I put a "use" statement for each CPAN module inside my methods as needed.
Why don't you just put them on the top of your modules code?


holli, /regexed monk/

Replies are listed 'Best First'.
Re^2: Using a module more than once
by kwaping (Priest) on Aug 02, 2005 at 15:22 UTC
    I guess I could do that - thanks for the suggestion! I just wanted to load them situationally, as not all of them are needed for every method. Or am I misunderstanding how that mechanism works?
      Or am I misunderstanding how that mechanism works?
      You are. Any module that gets used, will be loaded at compile time, thus, when your module is loaded. So there's no use in putting a use statement inside a method.

      Sometimes, when some modules are only needed in exceptional circumstances, people can use a require statement in a method or sub, for example to load Carp in an error trapping routine.

      You have to be aware of the differences between use and require: require doesn't call import in the loaded modules, and it won't change the allowable syntax for your code either. Thus, subs defined in that module won't be easily recognized as such in the loading script. It's something to look out for.

      For OO modules, it makes no difference, whether you choose use or require.

        However, as I understand it, you can delay use calls if you are using SelfLoader and then execute the use call inside of a subroutine.

        Example:
        use SelfLoader; sub __PACKAGE__::myfunc; 1; __DATA__ sub myfunc { use ThisOtherModule; }
        Great, thanks for the clarification! I'll switch to one of those other styles (either doing all the "use" statements at the head of the file, or using require instead).
      You're misunderstanding. use happens at compile time. Consider:
      #file: /perl/site/lib/Foo.pm package Foo; use strict; use warnings; sub bar { return "BAR"; } 1; #file: test.pl use strict; use warnings; my $i = 0; if ( $i ) { use Foo; } print Foo::bar; #prints "BAR"


      holli, /regexed monk/