Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Where and when you should place 'use module;'?

by mulander (Monk)
on Oct 12, 2005 at 12:24 UTC ( [id://499458]=perlquestion: print w/replies, xml ) Need Help??

mulander has asked for the wisdom of the Perl Monks concerning the following question:

Hellow fellow monks.
My question may seem rather simple but I haven't found the anwser either in perl documentation and the super search.
Here is my problem, I have a bigger script wich let's say uses 3 different modules, these 3 modules are only used in some subrutines so we can assume:
Module1, Module2, Module3
sub1, sub2, sub3
The sub 1 uses only Module1 and Module1 is not used anywhere else in the script, the equivalent is for sub2 and sub3. Now my question is of this nature:
Where should I include my modules? If I put the use Module1; use Module2; use Module3; on top of my script I assume that it will be loaded for the whole script witch is not what I want becouse it is only used in some subrutines, not the whole script. I was thinking about puting use Module1; inside sub1 code blocks but three questions came to me as I pondered about it.
Question 1, will the module be loaded for the whole script or just this sub?
Question 2, will the module be loaded each time I call the sub, or maybe just once on startup, or will it be loaded only once when I first time call the sub?
Question 3, if I i put use Module1; inside the subrutines code blocks, will the module be unloaded when the subrutine ends?

Thank you for the time you all sacrificed to read this node ( or maybe even anwser it ;) ) and I hope that none of you will be offended by such a simple question ( well simple for you beacouse my mind seems rather confused by this case ;) ).
  • Comment on Where and when you should place 'use module;'?

Replies are listed 'Best First'.
Re: Where and when you should place 'use module;'?
by muntfish (Chaplain) on Oct 12, 2005 at 12:43 UTC

    A use Module will cause the module to be loaded when the program starts, regardless of where in the script you put it (it gets run in a BEGIN block).

    I personally think it makes more sense to put all your "use" statements at the start of your script, that way you can easily see what your dependencies are - no nasty surprises.


    s^^unp(;75N=&9I<V@`ack(u,^;s|\(.+\`|"$`$'\"$&\"\)"|ee;/m.+h/&&print$&
      I also like to put all the "use" statements at the top, with one exception, and i believe this is what OP is looking for:
      use ModuleUsed::LoadedAt::CompileTime; sub sub1 { require Module1; # loaded at runtime ... } ...
      By using a require statement, the module will only be loaded at runtime of that line, which means IFF sub1() is called. The huge advantage here is that Module1 is only loaded into memory when (if ever) needed, which could be a big time/memory saver if it is a large module, especially if memory footprint is an issue.
Re: Where and when you should place 'use module;'?
by haoess (Curate) on Oct 12, 2005 at 12:52 UTC

    If your modules where only used sometimes, i. e. not every sub is called always when your program runs, you could require them:

    sub only_uses_sometimes { require My::Module; # and call import, if you want some exported things }

    Now the module will be loaded at run time.

    --Frank

Re: Where and when you should place 'use module;'?
by Moron (Curate) on Oct 12, 2005 at 12:44 UTC
    1), 2) & 3) perl doesn't care whether the 'use' is inside or outside a subroutine - 'use module' statements have file(*) scope.

    'use pragma' statements are different, for example, 'use integer' has block scope.

    Update: (*) or package scope if applied within the scope of a package declaration.

    -M

    Free your mind

      'use module' statements have file scope.

      They have package scope. Or rather, the require portion has program scope, the import portion has package scope.

      package Foo; use Benchmark qw{cmpthese}; package main; cmpthese( -1, { ...etc... } ); __END__ Undefined subroutine &main::cmpthese called at - line 7.

      update: It's worthwhile to add that import acting in package scope is conventional, not a rigid truth. import is free to do what it wants, but it is usually defined by Exporter (or like Exporter) to inject symbols into the caller's package scope.

        That's a bit misleading. Benchmark::cmpthese will be available in your entire program - in both packages. And so will Foo::cmpthese, for that matter. "package scope" is a bit of a misnomer, as there isn't a place where a package end (unlike a lexical scope).

        I like to compare the package statement to the effects of cd. And if you do:

        cd /Foo # package Foo; ln /Benchmark/cmpthese cmpthese # use Benchmark qw{cmpthese}; cd ~ # package main; ./cmpthese # cmpthese();
        you get "no such file or directory". But that doesn't mean the link /Foo/cmpthese has ceased to exist.
        Perl --((8:>*
Re: Where and when you should place 'use module;'?
by polypompholyx (Chaplain) on Oct 12, 2005 at 13:04 UTC

    A module is loaded at compile time, no matter where you place the use Module (except in an eval STRING). A module cannot be 'unloaded', although those that specify an unimport may allow you to turn off any semantics that they export using no Module. If you want a module to be loaded only on first demand, you could require it instead.

    I personally prefer to put all my use statements at the top of the file (so I know which modules my code needs to run in a single glance), although others may prefer to put them in the subroutines that actually need their functions/semantics.

    I wasn't expecting this though:

    use strict; use warnings; foo(); print Dumper [4,5,6]; sub foo { use Data::Dumper; print Dumper [1,2,3]; } print Dumper [7,8,9];

    __CONDENSED_OUTPUT__ $VAR1 = [1,2,3]; print() on unopened filehandle Dumper at D:\perl\t.pl line 4. $VAR1 = [7,8,9];

    Why isn't the third print Dumper 'correctly misinterpreted'?

      Why isn't the third print Dumper 'correctly misinterpreted'?

      I'm not exactly sure, but it looks like perl makes the decision whether that's a filehandle or a function call at compile time, and it doesn't make that decision properly until the symbols are actually loaded (which happens when the use line is reached). And since this is all compile-time behavior, the fact that use is wrapped in an implicit BEGIN block doesn't come into play yet.

Re: Where and when you should place 'use module;'?
by jZed (Prior) on Oct 12, 2005 at 13:11 UTC
    Look into require - it is similar to use but happens at run time rather than compile time. It only loads the modules if the subroutine it occurs in is run. You may need to import the module in addition to requiring it.
Re: Where and when you should place 'use module;'?
by jbrugger (Parson) on Oct 12, 2005 at 13:32 UTC
    Depends, if using mod-perl try loading them in the startup.pl, so they're precompiled and used in the shared memory. Else, i'd use require module to make sure it's only used (and compiled) as needed.

    "We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://499458]
Approved by Skeeve
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 10:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found