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

This question deals with what subs get loaded into my namespace and when are they loaded (startup or runtime). Lets use the CPAN module CGI in the example. Look at the two cases below:
# Case 1 use CGI qw(:cgi); my $value = param("Name");
As opposed to doing the following:
# Case 2 use CGI; my $q = CGI->new; my $value = $q->param("Name");
It is my understanding that Case 1 will load a whole bunch of subs because of the EXPORT tag :cgi. What happens in Case 2? Are only the subs loaded that the handle $q references? When do they get loaded? Is there any documentation that addresses this area? I think this has to do with Autloader and SelfLoader but I am fuzzy on the things I have read about these topics.

Replies are listed 'Best First'.
Re: What gets loaded
by daxim (Curate) on Jul 27, 2012 at 16:18 UTC
    What happens in Case 2?
    You must know use CGI qw(:cgi); is equivalent to
    BEGIN { require CGI; CGI->import(qw(:cgi)); }

    use CGI; is equivalent to

    BEGIN { require CGI; CGI->import(); }

    So the import method is passed no parameters. It depends on the type of exporter used, if any, what happens then. For example, the standard module Exporter will export the tags/symbols in @EXPORT. Filling @EXPORT is a bad practice for module authors for this reason. CGI loads a lot of unwanted stuff by default, see chapter USING THE FUNCTION-ORIENTED INTERFACE. Hm, turns out CGI doesn't do much by default, I must've been misremembering.

    It is a good practice for module consumer to always specify the minimum amount of symbols to import. It saves compile time and memory, and since import can do anything, not only export symbols, it avoid unnecessary side-effects. Most of the time, you simply want an empty list. use CGI qw(); is equivalent to

    BEGIN { require CGI; }
    Are only the subs loaded that the handle $q references?
    No; and you are conflating methods with subroutines.
    Is there any documentation that addresses this area?
    Follow perldoc -f import
    I think this has to do with Autloader and SelfLoader
    No.
Re: What gets loaded
by choroba (Cardinal) on Jul 27, 2012 at 15:55 UTC
    You might be interested in Exporter. The second case you show uses the Object Oriented approach, it is something completely different.