[Wellington-pm] A question about scopes

Cliff Pratt enkidu at cliffp.com
Tue Mar 21 01:39:40 PST 2006


Grant McLean wrote:
> 
>>If I make $bar "global" to the package, is there a clever way of 
>>avoiding qualifying it all the time to distinguish it from the script's 
>>version of $bar?
> 
> I'm not sure what you're asking here.
> 
> Perl has all sorts of clever tricks for aliasing variables (or subs) and
> importing them from one package into another.  But you should almost
> never do that.
> 
> Perhaps if we saw some of your real code, we might understand your
> intent more clearly.
> 
Sorry, I didn't mean to be obscure! I've actually solved the problem.

I have a little game/puzzle thing written in perl, outputting to the 
command line. I decided to update it and change it to use GTK2. I keep 
the game information in a list of 'elements' which I called @grid. When 
I started to write the GTK2 stuff I used the same name, @grid. To save 
rewriting I decided to make the old program into a package and 'use' it 
in the GTK2 script. So now I'm learning GTK2 *and* how to write packages....

Erm, anyway, say the main script is like this:

use MyGame ;
.
my @grid ;
.
.
# Recent change - I now pass the grid to the packaged sub and
# return it when modified.
@grid = MyGame::sub1(@grid) ;
.
.

The package is like this:
.
package MyGame;

# Recent change - This now outside any sub.
my @grid ;

sub sub1 {
	# @grid, but which one?
	@grid = @_ ;
	.
	return @grid ;
}

And it compiles fine. The problem was that the @grid list was defined 
inside a sub, so was local to the sub. Duh! I should've spotted that!

Now to see if it works....

Cheers,

Cliff
-- 

http://barzoomian.blogspot.com


More information about the Wellington-pm mailing list