[Wellington-pm] A question about scopes

Jacinta Richardson jarich at perltraining.com.au
Sun Mar 26 03:09:34 PST 2006


Cliff Pratt wrote:

> 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...

private methods are usually preceded by an underscore:  _check_element.  They're
still methods and are called and act the same way, but they're not typically
documented as part of the API.


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


Of course, if _check_element doesn't *need* to know anything about the object,
(that is, it's not a method) then it's just a regular subroutine and you'd call
and define it as such (which is what you had done).

private methods rely on programmers behaving because it's polite, not because
you force them to do so.  There's some quote here about a shot-gun, but I can't
remember it off the top of my head.  This would apply too to private subs.
After all, the programmer usually has access to your source code when they "use"
your module, so they can break any strictures you set up anyway.

All the best,

      Jacinta

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Wellington-pm mailing list