in reply to Lexical and dynamic scope confusion!

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

Replies are listed 'Best First'.
Re^2: Lexical and dynamic scope confusion!
by GoCool (Scribe) on Mar 27, 2005 at 06:06 UTC
    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