CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner: Re: [ChopperCharles] private and protected methods: Edit Log


Mar 30, 2012, 7:12 AM

Views: 16776
Re: [ChopperCharles] private and protected methods

Let me clarify, the return code that you are getting in is -1.
That is correct, however, the value you are testing for failure is 0, which is success. Your if statement is incorrect.

I understand what you want to do. The previous __foo I showed would only lock it down to the parent. To allow only the parent and any of its children to access it, you would need to check if the object isa fooBar.

sub __foo { #private  
my $name = shift;
if (ref($name)) {
my $self = $name;
unless ( (caller)[0]->isa( ref($self) ) ) {
$m_LastError = "Access to private method denied.";
return -1;
$name = shift;
print "Hello $name.\n";
return 0;

Also, in checking the retcodes needs to be fixed.

my $ret_code = 0; 

print "TacoBell:\n";
my $t = TacoBell->new();
$ret_code = $t->iAmfooBar();
if ($ret_code) { print "t->iAmfooBar() failed.\n"; }
$ret_code = $t->__foo("Charles");
if ($ret_code) { print "t->__foo(\"Charles\") failed.\n"; }

print "fooBar:\n";
my $fb = fooBar->new();
$ret_code = $fb->iAmfooBar();
if ($ret_code) { print "f->iAmfooBar() failed.\n"; }
$ret_code = $fb->__foo("d'oh");
if ($ret_code) { print "f->__foo(\"d'oh\") failed.\n"; }

Hello fooBar.
t->__foo("Charles") failed.
Hello fooBar.
f->__foo("d'oh") failed.

This shows that IAmfooBar is running the private __foo which is correct.
The fails occur when tries to access them directly.

Other than this, I don't know of another way to enforce private subs. Maybe using a closure in Not sure.

Perl doesn't enforce private, everything is public. Private is done by convention, meaning its upto the programmer to KEEP it legit. Usually, when methods begin with underscores, it's a message to other programmers that this really should be treated as private and ignore it. Otherwise, there is no guarantee it will not break your app in the future.

You may want to look over the OO perldoc, they are really worth the time.
perlboot Perl OO tutorial for beginners
perltoot Perl OO tutorial, part 1
perltooc Perl OO tutorial, part 2
perlbot Perl OO tricks and examples

Otherwise, you may need to look into using Moose or other Class modules.

Perl 5.1 is quite old. I would ask to update to at least 5.12 if possible.

(This post was edited by budman on Mar 30, 2012, 7:22 AM)

Edit Log:
Post edited by budman (User) on Mar 30, 2012, 7:22 AM

Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives