I was just showing you an example to explain the scoping.
In a working situation it just depends on what you need @context for.
my @context allows you to declare @context local to where ever it's
declared.  So:

my @context = qw( test1 );
{
        @context = qw( test2 )
        print @context
        prints "test2"
}
print @context
prints "test1"

As far as using @context vs. @MyApp::context inside MyApp, there is no difference. It's one of those many ways to do the same thing you hear about a lot in perl coding.
I myself use an OO approach:

package MyApp;

sub new {
        my $class = shift;
        my $this = {};
        bless( $class, $this )
        return $this;
}

package SomeOtherApp;

my $app_obj = new MyApp;
$app_obj->{context} = [ "test" ];

It makes it easier to keep it all sorted out for me...

Boysenberry

boysenberrys.com | habitatlife.com | selfgnosis.com

On Aug 20, 2005, at 8:52 AM, Christopher H. Laco wrote:

Boysenberry Payne wrote:

Each @context would persist as long as the packages exist above.
Each apache child ought to have it's own @context arrays regardless
of whether it's compiled by including it in a startup.pl type use at
apache start up, or required at runtime.


Then what's the point of using my @context vs. @MyApp::context if my @context persists as long as the package does?

From practical mod_perl:


6.4.3. Global Variable Persistence

Under mod_perl a child process doesn't exit after serving a single request. Thus, global variables persist inside the same process from request to request. This means that you should be careful not to rely on the value of a global variable if it isn't initialized at the beginning of each request. For example:

# the very beginning of the script
use strict;
use vars qw($counter);
$counter++;

relies on the fact that Perl interprets an undefined value of $counter as a zero value, because of the increment operator, and therefore sets the value to 1. However, when the same code is executed a second time in the same process, the value of $counter is not undefined any more; instead, it holds the value it had at the end of the previous execution in the same process. Therefore, a cleaner way to code this snippet would be:

use strict;
use vars qw($counter);
$counter = 0;
$counter++;

In practice, you should avoid using global variables unless there really is no alternative. Most of the problems with global variables arise from the fact that they keep their values across functions, and it's easy to lose track of which function modifies the variable and where. This problem is solved by localizing these variables with local( ). But if you are already doing this, using lexical scoping (with my( )) is even better because its scope is clearly defined, whereas localized variables are seen and can be modified from anywhere in the code. Refer to the perlsub manpage for more details. Our example will now be written as:

use strict;
my $counter = 0;
$counter++;

Reply via email to