mephit has asked for the wisdom of the Perl Monks concerning the following question:
Quick background: I want to use a module if it exists, otherwise use another, then create a file-scoped lexical object of the appropriate class. This would best be done in a BEGIN block, I've figured out.
After a few Super Searches, I figured out a few ways to set a file-scoped variable within said BEGIN block, and I'm wondering which is the Best Way, or if it's just a matter of programmer preference.
I have all methods incorporated in the code snippet below, so I wouldn't have to illustrate things four times. They all work, except for the $our_var method. I find this odd, since a "use vars" variable works, but "our" doesn't. Aren't the two the same thing?
Thanks to tye and this node for pointing out that a 'my' var declared before a BEGIN block won't cause problems. I assumed that it wouldn't work, but it does. Yay.
Anyway, here's my code:
So, which is best? Is that even a real closure? And why doesn't the $our_var method work? Thanks for any help, folks.use strict; my $pre; BEGIN { my $closure; our $our_var; use vars qw/$vars/; if (eval {require CGI::Safe} ) { CGI::Safe->import(); $closure = CGI::Safe->new; $vars = CGI::Safe->new; $pre = CGI::Safe->new; $our_var = CGI::Safe->new; } else { $< = $>; delete @ENV{qw(IFS CDPATH ENV BASH_ENV SHELL PATH)}; require CGI; CGI->import( qw/ :standard / ); $CGI::DISABLE_UPLOADS = 1; $CGI::POST_MAX = 512 * 1024; $closure=CGI->new; $vars=CGI->new; $pre=CGI->new; $our_var=CGI->new; } sub get_obj { return $closure }; } my $q = get_obj(); printf "object in 'closure' method is of class %s\n", ref ($q); printf "object in 'usr vars' method is of class %s\n", ref ($vars); printf "object in 'my' method is of class %s\n", ref ($pre); #printf "object in 'our' method is of class %s\n", ref ($our_var);
Mephit
--
There are 10 kinds of people -- those that understand binary, and those that don't.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Setting lexicals in a BEGIN block.
by chromatic (Archbishop) on Jun 21, 2002 at 01:56 UTC | |
by Juerd (Abbot) on Jun 21, 2002 at 07:04 UTC | |
Re: Setting lexicals in a BEGIN block.
by Juerd (Abbot) on Jun 21, 2002 at 07:11 UTC | |
by Anonymous Monk on Jun 21, 2002 at 07:58 UTC | |
by Abigail-II (Bishop) on Jun 21, 2002 at 09:25 UTC | |
by Anonymous Monk on Jun 21, 2002 at 10:30 UTC |