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

Hi Monks,

I was wondering if there is a difference if you declare your module requirements at the beginning of your scripts or within a subroutine that uses it.

e.g.

use strict; use CGI; blah, blah, blah sub cgi { my $cgi = new CGI; blah, blah }

vs.

use strict; blah, blah sub do_cgi { use CGI; my $cgi = new CGI; blah, blah, blah }

2nd question; is there a difference if I declare usage for subroutine before getting passed variables in a subroutine?

e.g.

sub do_stuff { my $one, $two, $three = @_; use CGI; }

vs.

sub do_stuff { use CGI; my $one, $two, $three = @_; }

Question 3; I've realised that you can use modules in different ways e.g. use CGI or use CGI qw(:all). What is the difference?

Thanks.
Desmond

Replies are listed 'Best First'.
Re: writing subroutines, differences in method of writing
by eibwen (Friar) on May 05, 2005 at 06:30 UTC

    As was recently explained to me in a similar node, use module; statements are enclosed within an implicit BEGIN { } block.

    With regard to your second question, there is no difference between the relative placement of the use statement as it is implicitly located within a BEGIN { } block, rendering the two codes identical.

    The answer to your third question can be found in perlfunc under use, but suffice it to say the list corresponds to the module's exports, thus allowing selective importation of the module.

      In follow-up to that. I'd recommend keeping any use and require statements at the top of the script. It allows the next guy who needs to maintain your script an easy view of which modules it is using all in one group instead of having to search on the use and require commands to find them dispersed throughout the different subroutines.
Re: writing subroutines, differences in method of writing
by revdiablo (Prior) on May 05, 2005 at 16:37 UTC

    One quick note. my $one, $two, $three = @_; probably does not do what you want it to do. Check out the dump of how it's actually being parsed by perl:

    $ perl -MO=Deparse,-p -le 'my $one, $two, $three = @_' -e syntax OK (my($one), $two, ($three = @_));

    We see that the syntax is "OK", meaning it's not a syntax error, but it doesn't really make sense to want to do that. You probably meant my ($one, $two, $three) = @_;.

Re: writing subroutines, differences in method of writing
by sandrider (Acolyte) on May 07, 2005 at 01:28 UTC
    Thanks guys. :)