[Wellington-pm] A question about scopes

Cliff Pratt enkidu at cliffp.com
Sun Mar 26 01:50:35 PST 2006


Grant McLean wrote:

[snipped stuff that is no longer relevant]
> 
> 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 :-)
> 
I think my brain just exploded.....

Well, I'm objectifying my programs/packages and I've got to the point
where the program can call a couple of methods (including a constructor)
on an object. I've hit a snag, though when trying to write what might be
called 'internal' or 'private' subs in the package. In the snippets 
below sub calc_move is a method of foo. It calls check_element which is 
not called from outside of Package foo. What's the best way of getting 
access to the object data from within check_element, which is not an 
object method call. Or maybe it is. I feel that I'm missing something 
obvious...

Package foo;
.
.
sub new {

  	# Current object is a hash to a list of elements:
  	# 	$hash = { GRID => @grid } ;
  	# 	
  	my $class = shift ;
  	my $self = {} ;
  	$self->{GRID} = [] ;
  	for ($i = 0 ; $i < 81 ; $i++) {
  		$self->{GRID}[$i] = 'aaa' ;
  	}
  	bless $self, $class ;
}

sub grid {
  	# This method gives access to the @grid array.
  	my $self = shift ;
  	if (@_) { @{$self->{GRID}} = @_ }
  	return @{$self->{GRID}} ;
}

sub calc_move {
	# Calculate next move
	my $self = shift ;
	my $i ;
	for ($i = 0; $i < 81 ; $i++) {
	check_element($i) ;
	}
}

sub check_element {
	my $element = shift ;
	.
	.
}

Cheers,

Cliff

-- 

http://barzoomian.blogspot.com


More information about the Wellington-pm mailing list