Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

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

by polypompholyx (Chaplain)
on Oct 12, 2005 at 13:04 UTC ( #499469=note: print w/replies, xml ) Need Help??

in reply to Where and when you should place 'use module;'?

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\ line 4. $VAR1 = [7,8,9];

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

Replies are listed 'Best First'.
Re^2: Where and when you should place 'use module;'?
by revdiablo (Prior) on Oct 12, 2005 at 20:31 UTC
    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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://499469]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2018-05-27 22:38 GMT
Find Nodes?
    Voting Booth?