http://qs321.pair.com?node_id=276941

Personally I almost always 'use' require unless I have some pressing need for magic in the module that requires the import sub to be called. I just dislike the namespace pollution that calling 'use' entails, such as not knowing exactly what functions it imports. Of course I could read the docs and find the list of functions.. unless of course the docs are out of date..

But I don't like having the function imported anyways, whether I know what the name is or not. I vastly prefer 'Foo::Baz()'; as when it functions as self commenting code, when I return to the module 6 months later I can instantly look at it and say "I know where that function is", as opposed to wandering around through dozens of other modules. So what do you prefer? The laziness of use or the preciseness of require?

Replies are listed 'Best First'.
Re: USE or Require?
by chromatic (Archbishop) on Jul 22, 2003 at 22:37 UTC

    False dilemma.

    use happens at compile-time while require happens at run-time. There's a big difference. You can also control what's imported into your namespace by providing arguments to use — besides that, there's no reason import() has to export anything. Several modules use different behavior based on what you pass to import(), and if you only use your "precise" require, you'll miss out.

      Also, if the module requires actions at CHECK or INIT time you've just cut that functionality out - runtime happens after INIT and CHECK so whatever initialization the module was expecting will never occur. That's a good reason to use 'use()' right there.

      Sigh. Perhaps I chose terms that were too specific for the attitudes I was trying to convey. You certainly choose to debate the merits of the specifics rather then the nature of the general.

      My main point was not to nit pick the differences between use and require, but rather to look at the question of "Is it false lazyness to import subroutines/vars/etc into your namespace?". It's lazy in a good way because you don't have to type endless amounts of semicolons, but then it's lazy in a bad way because you don't know exactly where the subroutine came from. Obviously I favor the latter arguement, that "Foo::Baz()" is preferable to "Baz()" due to it's self documenting nature, it lets you know exactly where the subroutine is coming from and what it corresponds to.

        Okay, that's a different question and worth more thought.

        I don't have a problem importing things into my namespace for three reasons:

        • I keep my code fairly short, so I don't have to import many things.
        • I tend to import only the things I really want, so the use line explicitly says what I want.
        • When I bend my second point, I only do so with well-defined idioms, such as with the Test::* modules or something like File::Path.

        I expect someone maintaining my code to be able to find the original location of functions I've imported. I try not to make it hard on that person, but I don't believe in writing un-idiomatic code because it's perceptually "self-documenting". Part of maintainability is readability and duplicate code hurts that.

        I'll second chromatic and add:

        • If you ever feel like getting a drop-in replacement you'd need to do dangerous things.

        I generally dislike hardcoded things, and using a fully qualified name is no exception.

        ihb

        I think using require is false lazyness. And the points that were made about require are very valid and pertinent to the discussion of using one over the other. IMO its use unless you have _very_ good reason to want to use require. And one of those points that is sofar unmentioned (I think) is that prototypes arent respected by code that is 'required'.


        ---
        demerphq

        <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...
Re: USE or Require?
by perrin (Chancellor) on Jul 23, 2003 at 02:37 UTC
    If your goal was to talk about importing, you shouldn't have brought use and require into it. The preferred way of loading modules in Perl 5 is use and if you don't want to import anything you just say use CGI (), with an empty list as the last parameter. It only makes sense to use require when you are loading the module at run-time.
Re: USE or Require?
by Dog and Pony (Priest) on Jul 23, 2003 at 03:57 UTC
    I just dislike the namespace pollution that calling 'use' entails, such as not knowing exactly what functions it imports.

    If the docs aren't enough, check the source. And if that isn't enough either, the call use with parameters, as in:

    use CGI qw(:standard);
    or for that matter,
    use CGI ();
    to import nothing. use is done at compiletime, and thus IMO is preferable in most cases. I only use require when I need to do conditional inclusion of something.


    You have moved into a dark place.
    It is pitch black. You are likely to be eaten by a grue.
Re: USE or Require?
by skyknight (Hermit) on Jul 23, 2003 at 12:49 UTC

    Oft times questions of the form "is X better than Y?" are largely meaningless without context information. Are pickup trucks better than minivans? Well, it depends whether you're planning on hauling around lumber or half a soccer team's worth of children. Looking at other replies and your responses it looks as if you had two questions; I'll try to answer both.

    The use keyword executes code at compile time where as require does it at run time. Almost always you want the former, though I can give you an example of where I personally want the latter. I have a class called SQLLink that is fed information about a link table in a SQL database. Among the information there are table specifications, but also the class names of the parent and child classes. I use 'require' to compile the code for a parent or child class when SQLLink needs to instantiate such a class.

    eval "require $parent_class"; die "$@\t...$parent_class barfed" if $@; eval "require $child_class"; die "$@\t...$child_class barfed" if @;

    You need the idiom of the string eval (to the best of my knowledge) to get 'require' to do its bare word behavior of locating a class based on your lib paths, and because eval traps errors you'll want the 'die' afterwards to make sure that the file compiled successfully.

    Now to address what would seem to be your real question, whether tis nobler to pollute thy namespace, yada yada outrageous fortune and so forth. Personally, I really hate namespace pollution for the same reason you do. I do not want to see "foo()" in the code, not be able to find "sub foo { ... }" anywhere in my code, and notice that there are ten library importations at the top of my code and have no clue where to start looking to figure out from where foo originated. To refer back to my 'context' assertion from the first paragraph... It matters whether you're writing a throw away script that fits in a single screen full of code that you don't plan on using after this afternoon, or if it's a serious attempt at a core library to which you (and other people!) will be frequently returning, or worse still infrequently, as the longer you go without looking at it, the less likely you're going to remember how it worked.

    Fortunately, there is what I deem to be a very good compromise. Any module worth its salt not just jams an @EXPORT variable full of junk, but also populates an @EXPORT_OK variable which specifies which names it is ok to explicitly export. I think the really nasty namespace pollution comes is the implicit kind, but explicit pollution is ok in my books. If you come across "foo()" in your code, and then you go to the top of your library and you see...

    use Some::Module qw(foo);

    it is obvious at a quick glance from whence foo sprung. You also know from that statement that foo was the only thing that Some::Module exported, since no implicit exportation occurs if you specify anything explicitly. So, I believe you very justified to eschew implicit namespace pollution, but give the explicit variety a chance. I think you'll like it.

Re: USE or Require?
by castaway (Parson) on Jul 23, 2003 at 07:28 UTC
    You can always do both. Importing subroutines doesn't actually prevent you from explicitly calling them using the package name in your code.

    (I use 'use' for reasons others have mentioned, but usually call subs using package names, or creating objects.)

    C.

Re: USE or Require?
by hardburn (Abbot) on Jul 23, 2003 at 15:52 UTC

    I find that modules that export by default aren't a big deal as long as the sub names are descriptive and you keep your use statement tight to the code that needs it.

    For instance, the Compress::Zlib module exports compress() and decompress() automatically. In a recent bit of code, I wrote something like this:

    my $data = 'mumble'; use Compress::Zlib; my $compressed = compress($data);

    It should be fairly obvious, without reading the Compress::Zlib docs, where compress() comes from.

    I will concede the point that this is not always possible, and that you often have little control over the sub names of a module.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

Re: USE or Require?
by sauoq (Abbot) on Jul 23, 2003 at 21:52 UTC

    I only use require when I need to load a module I've been trying to avoid using. For example, I don't use Carp; but, instead, I require Carp; once I've encountered an error and need to carp() or croak(). As another example, I sometimes require Data::Dumper; if a debug flag is set.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: USE or Require?
by l2kashe (Deacon) on Jul 23, 2003 at 17:57 UTC

    On the flip side, the only routine I export is new, and that goes in EXPORT_OK. I tend to shy away from writing libs, in a non OOP style. I hate namespace corruption, and I simply don't want to afflict it on the next person in line. With that said I try to do use module (); when I remember. I almost never directly access stuff outside of main's namespace, the only exception I can think of is File::Find, which irks me to no end everytime I use it, but *shrug*

    use perl;

      On the flip side, the only routine I export is new, and that goes in EXPORT_OK.

      Why on earth would you want to export new in OO code (he asks curiously :-) ?

        Why on earth would you want to export new in OO code

        I struggled with this one for a while myself, wondering what the idea might be, and I have come to a hypothesis, however shaky. :-) If we want to use a common class framework amongst many classes but dont want them to have a common ISA ancestor then we might make a module like

        package ObjectPrototype; use base qw/Exporter/; @EXPORT=qw(new); sub new { my $class=shift; bless {@_},$class }

        so now we can say

        package Foo; use ObjectPrototype; package Bar; use ObjectPrototype;

        without establishing an ISA relationship between any of the module/classes involved.

        I admit however that the only reason I could think that this would be useful is if you were doing some funky by hand @ISA tree walking in your code. Having only done this once myself I dont see it being needed much. Although now the thought has come to me... :-)


        ---
        demerphq

        <Elian> And I do take a kind of perverse pleasure in having an OO assembly language...

        I attempt to maintain a consistant paradigm. If I need to use the functionality from another module, I instantiate an object and use the defined API. If I need a series of objects, I instantiate them in my constructor and store them in my constructor. I guess only exporting new which is kind of redundant anyway, is bascially stating "Here is the way I would like you to come in, see that API over there, that's for you". If people end up editing the source to export more, or set up inheritance, more power to them.

        Granted it's not the only way to do it by any means, and I give up some functionality, but I prefer the consistancy in all my code produced for this company. In my current position, each module produced is pretty close to the bottom of the food chain. I think if I were providing slightly more generic modules the case may be different, but in the present situation its not necessarily the best solution.

        use perl;