http://www.perlmonks.org?node_id=664843

gnum.prul has asked for the wisdom of the Perl Monks concerning the following question:

Hi All!

I'm wondering where can I find an in-depth documentation on how require/use work scopewise? Let's say I have:
sub coolsub { require Mod; ... }

What does really happen here? How does it differ if I require Mod outside of any subroutine/block?

Thanks!

Replies are listed 'Best First'.
Re: 'require/use' scoping
by shmem (Chancellor) on Jan 29, 2008 at 07:12 UTC
    What does really happen here?

    The source file for module 'Mod' is searched, read and compiled at run time, as opposed to use, which would lead to compilation of the module at compile time of the script which contains that 'use' statement.

    Nothing special about scoping here. The namespace of the module 'Mod' is defined after successful compilation, and it has its own scope. The visibility of that namespace is not confined to the block which contains the 'require', it is available to all perl code executed thereafter, no matter if it's in the same scope or even the same file.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: 'require/use' scoping
by plobsing (Friar) on Jan 29, 2008 at 05:12 UTC
    It costs you nothing to test it out. Give it a whirl, see for yourself.

    Some things to try (assuming Mod has something in it):
    print "Mod loaded at 1" if %{Mod::}; require Mod; print "Mod loaded at 2" if %{Mod::};
    print "Mod loaded at 1" if %{Mod::}; use Mod; print "Mod loaded at 2" if %{Mod::};
    print "Mod loaded at 1" if %{Mod::}; sub require_it { require Mod; } print "Mod loaded at 2" if %{Mod::}; require_it(); print "Mod loaded at 3" if %{Mod::};
    print "Mod loaded at 1" if %{Mod::}; sub use_it { use Mod; } print "Mod loaded at 2" if %{Mod::}; use_it(); print "Mod loaded at 3" if %{Mod::};
    As for the documentation, you could always try perldoc, pm super search, google, etc.

    And in case you realy want to know whats realy happening, the perl source code is freely available.
      Yes, I really want to know what's happening, i.e. I'd like to know how exactly requiring is different from eval `cat mod.pm`; as perldoc contains numerous code snippets showing how require works based on eval. I guess the source is the answer...
Re: 'require/use' scoping
by BrowserUk (Patriarch) on Jan 29, 2008 at 07:48 UTC

    There is one time when requireing a module will limit it's scope. When using threads:

    C:\test>perl -Mthreads -wle"async{require CGI; print 'T:'.%{CGI::}}->detach; sleep 2; print ' +M:'.%{CGI::};" T:61/128 M:0

    The above shows that a module required in a thread is not visible in other threads.

    But if you use it anywhere, it will be visible (and consume space) in all threads:

    C:\test>perl -Mthreads -wle"async{ use CGI; print 'T:'.%{CGI::} }->detach; sleep 2; print 'M: +'.%{CGI::};" T:62/128 M:62/128

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: 'require/use' scoping
by hipowls (Curate) on Jan 29, 2008 at 08:00 UTC

    The two main differences difference between use and require are

    • use is done during the initial compile phase whilst require doesn't happen until it is encountered during program execution.
    • require does not run the import function.
    The scope is the same for both, that is from the time they are first run until program exit.

    Typical usages include

    sub rarely_called { require Expensive::Module; }
    sub not_backwards_compatible { require 5.010_000; }

    require for pragmata probably won't do what you think since import is not run.

Re: 'require/use' scoping
by brian_d_foy (Abbot) on Jan 29, 2008 at 15:26 UTC

    [ Whenever someone asks you the difference between require and use, point them to the use entry in perlfunc. Not only will they get the right answer, but they'll learn how to use the docs. In this case, the OP wants to know about what require does and how it does it. Again, perlfunc has the answer. :)]

    Packages or namespaces are not scopes! This week I've seen a few people mention that, but it's not true and I don't know where people ever see that. Scopes are either blocks of code or the file, which has an implicit scope around all of its contents. The package pragma is scoped, but any symbol table work it does is not.

    These two are equivalent and there's nothing else special going on. It's not just a run-/compile-time thing. The use also implies an import.

    use Foo; BEGIN { require Foo; Foo->import; }

    Curiously, the answer in perlfaq8 on "What's the difference between use and require" is crap, so now I must go fix it. And so it has come to pass:

    Now, the other part of the OP's question is what require is actually doing. Again, it's right in perlfunc. This code is directly from the entry on require and shows exactly what you would have to do on your own to recreate its behaviour:

    sub require { my ($filename) = @_; if (exists $INC{$filename}) { return 1 if $INC{$filename}; die "Compilation failed in require"; } my ($realfilename,$result); ITER: { foreach $prefix (@INC) { $realfilename = "$prefix/$filename"; if (-f $realfilename) { $INC{$filename} = $realfilename; $result = do $realfilename; last ITER; } } die "Can't find $filename in \@INC"; } if ($@) { $INC{$filename} = undef; die $@; } elsif (!$result) { delete $INC{$filename}; die "$filename did not return true value"; } else { return $result; } }

    That little snippet is already assuming that a bareword has been turned into a filename, and doesn't do portable path construction, but it's the mechanics that count. Notice the do to actually run the code.

    --
    brian d foy <brian@stonehenge.com>
    Subscribe to The Perl Review
      Packages or namespaces are not scopes! This week I've seen a few people mention that, but it's not true and I don't know where people ever see that. Scopes are either blocks of code or the file, which has an implicit scope around all of its contents. The package pragma is scoped, but any symbol table work is does is not.

      The parts of the code where a variable is visible constitutes the scope of the variable. Lexical variables have a lexical scope and you've enumerated the lexical scopes in Perl (except that lexical scopes are subsets of those because they begin on the statement after the variable is declared). The scope for a(n unqualified) package variable is the package. This is not a lexical scope but it is a scope. local effects dynamic scope which is about the scope of the value rather than the variable (or, more precisely, of an instance of the variable). Dynamic scope is certainly not a lexical scope.

      The scope of the effect of symbol table manipulations is usually the symbol table, that is, the package. The scope of the effect of a lexical pragma is a subset of the lexical scopes that you enumerated, one starting at the statement after the invocation of the pragma (just like for lexical variables).

      - tye        

        Package variables are visible throughout the entire program. They have no scope. Don't confuse the default package with a scope. A default package doesn't limit the extent or effect of a variable. To use "scope" in that sense only confuses people and makes the word useless. In your sense, you could also talk about the "scope" of hash keys. It's not a useful concept when you extend it like that, and that's not it's meaning when you're talking Perl.

        local has nothing to do with the scope of the variable. It deals with the value of the variable during a lexical scope (but not within a lexical scope), and only works on package variables. The variable's value is available outside of its lexical scope (as in subroutines and so on).

        See the entry for package in perlfunc for details.

        Update: Tye, think what you like, but Perl isn't Wikipedia. When you talk about (Update: variable) scope in Perl, the time it makes any sense is in lexical scoping. Any other use of the concept is just wanking. It's not my personal definition: it's how it's used in the Perl documentation, which doesn't have any other (Update: variable) scope to talk about. Despite you're repeated claim about a package variable being scoped, it's just not true. It's always available everywhere in the program. The small matter of syntax about referencing it doesn't matter. As for what local does, don't conflate how it does it behind the scenes with what the feature is. You might also want to read Dominus's Coping with Scoping".

        --
        brian d foy <brian@stonehenge.com>
        Subscribe to The Perl Review
      Hey Brian!
      The package pragma is scoped, but any symbol table work is does is not.
      This is actually what I was asking about :) Thanks!
Re: 'require/use' scoping
by Anonymous Monk on Jan 29, 2008 at 07:13 UTC
    perldoc -f require
    perldoc -f use