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

Suppose module CGI.pm has a sub-routine named sub1 and i "use CGI" in my perl code and create a sub-routine named sub1 not knowing that a sub-routine with the same name already exists in CGI.pm. now if i declare and define sub1 and call it in my program using this syntax:
sub1();
which one will it refer to (assuming that both sub-routines have the exact same prototype)? i don't need to fully qualify the function name with the package name as it is imported at compile time using the "use" keyword. how do i stop this ambiguity from happening when i write a module and allow others to use my functions/subs and variables from my package?
Thanks in advance.
Gokul

Replies are listed 'Best First'.
Re: Lexical and dynamic scope confusion!
by Zaxo (Archbishop) on Mar 27, 2005 at 05:49 UTC

    If you don't import the CGI "sub1" through arguments like: use CGI qw/sub1 :standard/; the unqualified sub1 you call will be your own.

    This really has nothing to do with lexical scope, because sub names are always in the symbol table.

    Dynamic scopes can temporarily replace CGI's notional sub1 with your own like this (in namespace main::) :

    { local *CGI::sub1 = \&sub1; # do some CGI things }
    Locally changing CGI::sub1() to something else for the duration of a dynamic scope causes all the CGI uses of sub1 to find yours instead of CGI's.

    After Compline,
    Zaxo

      my understanding was that, and please do correct me if i'm wrong, when i say "use CGI" in my code, it exports everything that was specified in "@EXPORT_OK" list in the CGI.pm module. if sub1 is one of them, then it is imported into my program's symbol table even though i do not know of its existence (ofcourse, i can find out all the functions and varibles imported through 'use')
      back to the original question, if i declare and define a sub called sub1 and call it within my program, (again the function calls would be identical too as i don't have to fully qualify calls to subroutines that reside in the package that i import as long as it is imported through 'use package-name') which one is it referring to? how does CGI.pm module ensure that a call to sub1 is answered by it and not the one in my code? or does it even check for such a thing?

        No, you're thinking of @EXPORT. Names in @EXPORT_OK are exported only if asked for, by convention.

        CGI uses its own custom import routine instead of subclassing Exporter, but as far as I know it follows the perl conventions on this.

        If sub1() is in @EXPORT, then it is indeed imported to the namespace where use CGI; appears. In that case, the last-defined version is the one which is called (along with a redefinition warning).

        use CGI; sub sub1 {} # this one overwrites CGI's
        but,
        sub sub1 {} use CGI; # CGI's overwrites yours

        After Compline,
        Zaxo

Re: Lexical and dynamic scope confusion!
by Tanktalus (Canon) on Mar 27, 2005 at 06:24 UTC

    A little trial and error would answer the question as to what happens, although maybe not the "why" part. Here's what I wrote:

    use strict; use warnings; package Foo; use base 'Exporter'; our @EXPORT = qw(sub1); our @EXPORT_OK = qw(sub1 sub2); sub sub1 { print "Foo::sub1\n"; } sub sub2 { print "Foo::sub2\n"; } package main; #use Foo; BEGIN { Foo->import(); } sub sub1 { print "main::sub1\n"; } sub1();
    Note the "use Foo" is commented out - because I put this all in the same file, you can't quite do that, so I faked it with the next line - and the BEGIN is very important here. By using the BEGIN, it changed the output. With the BEGIN, I get "main::sub1" as the output, but without the BEGIN, I get "Foo::sub1" as the output.

    With the BEGIN is representative of "use"ing the module since "use" is handled during compilation, as is anything in a BEGIN block.

    I know others disagree with this, but the way I handle the ambiguity is to try to import as little as possible into my namespace - preferably importing nothing. And then I can call functions in other namespaces by fully qualifying the function call.

    Even better than that is to use an OO interface, if there is one available, but not everything makes sense as an object. (I think CGI does, but that's not necessarily universally accepted, either.)

    In absense of these (calling functions via fully qualified names, or OO syntax), import precisely what you need, no more, no less. This means you get to keep an exact list of what you're using from another module, and won't be as likely to have two functions in your module's namespace with the same name.

    It is highly discouraged to try to use a function "sub1" from another module, while exporting a different "sub1" from your own module. You're looking for a headache on that one - fully qualified names (for calling the other module's sub1, not for exporting your sub1) or OO syntax are quite a bit cleaner here.

      Just a few comments on your example. The first one is that to do what you want to do within a single file, you need to stick the initializations of @EXPORT and @EXPORT_OK in their own BEGIN block (otherwise they happen at runtime, which is to late for the (require-less) importation from Foo). To see this, try running your code with the line defining main::sub1 commented out. It fails with the error

      Undefined subroutine &main::sub1...
      even though you are importing from Foo and Foo exports a routine sub1. But if you put the initialization of @EXPORT in a BEGIN block, the code runs fine and you see the output:
      Foo::sub1
      (OK, I don't want to confuse anyone, so just to be perfectly clear, this business of sticking the initialization of @EXPORT (and @EXPORT_OK, @EXPORT_FAIL, etc.) in a BEGIN block is necessary here only because we are trying to "import" from within the same file, which is a very unnatural thing to do, and meant only for the purpose of testing and illustration.)

      If now you uncomment the definition of main::sub1 the code compiles and runs, but one gets a warning about redefining "sub1" (main::sub1 that is) that one didn't get before. (Which suggests that in the original version there really wasn't even the potential for conflict between the two sub1's, since Foo wasn't really exporting it after all.)

      A second point is that if (after putting @EXPORT, etc. in a BEGIN block) one puts the importing of Foo::sub1 after the definition of main::sub1, this will cause main::sub1 to be aliased to Foo:sub1 (as Exporter normally does), and no warning is emitted. To see this, try running the following code:

      use strict; use warnings; package Foo; use base 'Exporter'; BEGIN { our @EXPORT = qw(sub1); } sub sub1 { print "Foo::sub1\n"; } package main; sub sub1 { print "main::sub1\n"; } BEGIN { Foo->import(); } sub1(); main::sub1();

      The third point is that mentioning the same subroutine in both @EXPORT and @EXPORT_OK, as is the case with sub1 in the original example, defeats the purpose of @EXPORT_OK (namely to export only if the user explicitly requests it). In the the original example, Foo exports sub1 unconditionally, even though sub1 is mentioned in EXPORT_OK.

      the lowliest monk

      Update: Added a brief explanation in the first paragraph for why an extra BEGIN block is needed.

Re: Lexical and dynamic scope confusion!
by borisz (Canon) on Mar 27, 2005 at 08:25 UTC
    Another way to avoid this namespace conflicts is just do not import functions from other modules into yours.
    use CGI (); # call CGI's sub1 CGI::sub1(); # your sub1 sub1();
    Boris
      That will normally work, yes. However, some modules will only create functions when they are asked for in the use-line. So, doing something like:
      use Foo qw( bar ); bar();
      will work, but doing this won't:
      use Foo; Foo::bar(); # <-- BOOM!

      CGI isn't one of these, but the possibility is there.

      Being right, does not endow the right to be rude; politeness costs nothing.
      Being unknowing, is not the same as being stupid.
      Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
      Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

Re: Lexical and dynamic scope confusion!
by jZed (Prior) on Mar 27, 2005 at 05:39 UTC
    > how do i stop this ambiguity from happening when i write a 
    > module and allow others to use my functions/subs and 
    > variables from my package?
    
    One way is to create methods instead of functions and access them via an object. Your $cgi object will unambiguously call it's param() method and if your $foo object also has a param() method, there will be no ambiguity. If you insist on using functions, then, use export_ok() to make the user explicitly import the functions they want to use. That way, there will at least be a record in the script of which functions are imported from which module.