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

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

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

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

        I clearly state that it is the import portion of use that is scoped to the package, so I didn't think that it was misleading, but thank you for clarifying. My key point was that no aspect of a use module is file scoped, as the upthread post claimed.

        I see your point with respect to package scope, but I disagree. Scope means the area in which the symbols are immediately available and immediately effected - the current context or 'view'. In your example, the scope of an rm * is the CWD. If you cd to another directory, the scope changes, but the old scope isn't destroyed forever, it is just one step removed from the action.

        This is the difference between scope and extent. Lexicals have a dynamic extent - they persist only as long as you keep a window on that scope open. Package variables have limited scope but unlimited extent.