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

Background: I am working with a legacy CGI program that uses cgi-lib.pl and ReadParse(). (I know, don't say it.) I have written some new modules that I use in a file that's required by the main CGI. All this file contains is a single sub. My new modules use CGI.

Here's the strange part... I believe that use is a compile-time thing, and it doesn't matter where in the program the use statements are. However, I've discovered differently. If I use my modules in the required file inside the subroutine, everything works fine. However, if I use my modules outside the sub but still inside the required file, CGI.pm consumes the query string and ReadParse() from cgi-lib.pl comes up with nothing, breaking the whole program.

Does anyone have an explanation for this unexpected behavior?

---
It's all fine and dandy until someone has to look at the code.

Replies are listed 'Best First'.
Re: "use" location within a program - it matters??
by Zaxo (Archbishop) on May 26, 2006 at 23:30 UTC

    CGI is a better replacement for cgi-lib.pl, which is long obsolete. Your CGI->new constructor consumes the POST input leaving nothing for cgi-lib to chew on. CGI.pm has a compatibility mode you get by importing ":cgi-lib".

    use CGI qw/:cgi-lib/;
    See CGI for details.

    After Compline,
    Zaxo

Re: "use" location within a program - it matters??
by sgifford (Prior) on May 27, 2006 at 01:29 UTC
    use does happen at compile-time, but require doesn't. When you require the file from the main CGI, that file is compiled, and at that file's compile time, the use statements are executed.
Re: "use" location within a program - it matters?? (sometimes)
by tye (Sage) on May 27, 2006 at 01:29 UTC

    As to the title, sure, where you 'use' can make a difference. Moving a 'use' between inside and outside of a subroutine should make very little difference as to when the resulting require and import are called (but, of course, can have an impact on the context in which the import is called, such as with the lexically scoped pragmas such as strict.pm).

    So I don't see how what you described would happen. Of course, you show no code so I'm forced to imagine what you are doing. So I suspect that my imagination is failing me in its reconstruction of your situation rather than failing me in figuring out how the situation gives the described results. So you might want to produce a minimal test case that reproduces the problem so I don't have to imagine that part.

    - tye