[Wellington-pm] A question about scopes

Grant McLean grant at mclean.net.nz
Tue Mar 21 02:48:48 PST 2006


On Tue, 2006-03-21 at 21:39 +1200, Cliff Pratt wrote:
> 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) ;

To save all the copying back and forth, you could pass a reference to
@grid which would allow the module to modify the array back in the
script:

  MyGame::sub1(\@grid);

Then you could learn Gtk2, packages *AND* references.

> .
> .
> 
> The package is like this:
> .
> package MyGame;
> 
> # Recent change - This now outside any sub.
> my @grid ;
> 
> sub sub1 {
> 	# @grid, but which one?
> 	@grid = @_ ;

You could grab the reference like this:

          ($grid) = @_;

And then refer to an element in the referenced array:

          print $grid->[0];

Or loop over all the elements:

          foreach my $item (@$grid) {

> 	.
> 	return @grid ;
> }

But it does sound like your module would benefit from being turned into
an object.  That way you wouldn't need the global for @grid - you'd
store the reference in the object where it would be available to all
methods.  And if you instantiated two objects, they'd each have their
own grid.

As you know from my Glade article, I like to arrange for Gtk GUI events
to call methods on my object(s).  That way all the necessary state
information is available in the object without having to use globals.

That would have the added advantage that you could learn Gtk2, packages
*AND* references *AND* objects *AND* closures :-)

Cheers
Grant




More information about the Wellington-pm mailing list