Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have this package.
package Sample_Test; use strict; use Exporter; our $VERSION = 1.00; our @ISA = qw( Exporter ); our @EXPORT = qw(); sub New { my $class = shift; my $self = { user => 'me', num => '123', }; bless( $self, $class ); return $self; } sub _Print_Me { my ($self) = @_; print $self->{user}; } sub Show_Me { my ($self) = @_; return _Print_Me(); } 1
And I have this test script.
#!/usr/bin/perl use warnings; use strict; use Sample_Test; my $object = Sample_Test->New(); $object->_Print_Me(); $object->Show_Me();
When I run it, it only gives me the output from $object->Show_Me(). I think it is obvious why it is not working, but I cannot just figure it out.

Replies are listed 'Best First'.
Re: Simple OO Question
by Corion (Patriarch) on Sep 15, 2010 at 22:20 UTC

    That's not what I get:

    >perl -w tmp.pl Use of uninitialized value in print at tmp.pl line 25. me

    That is because in ->Show_Me, you're calling _Print_me while you should be calling ->_Print_Me instead:

    sub Show_Me { my ($self) = @_; return $self->_Print_Me(); # <-- }

      As an expansion: _Print_Me() is expecting an argument (a reference to a hash), which it puts in $self. It then prints the hash element user out of that argument.

      In your version of Show_Me, you don't pass it that expected argument. There are two ways to do so in this case: Using standard function notation (_Print_Me($self)) or using object notation, which implies the object itself as the first argument. ($self->_Print_Me())

        As a further expansion: The difference between _Print_Me($self) and $self->_Print_Me is that _Print_Me($self) will always use the current package's _Print_Me, while $self->_Print_Me will find the appropriate _Print_Me for the package (class) that $self is blessed into.

        As a general rule, you'll want to use _Print_Me($self) when you want to use one specific implementation, no matter what, and use $self->_Print_Me when you want to allow for polymorphism (which should be almost always, since you never know when $self might belong to a subclass which has overridden _Print_Me).