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

Hello monkers!

given a package with a constructor, is there a way to autoload the object itself to return a given value/subroutine value? i tried something like this:

package MyPackgage; sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self, $class; return $self; } sub AUTOLOAD { my $self = shift; return "ook?"; }
my goal is that if i $object = MyPackage->new(); then i can do print $object
and the returned value will be from whatever i autoloaded...

Replies are listed 'Best First'.
Re: Anonymous Autoloading with OOP?
by ikegami (Patriarch) on Oct 12, 2008 at 19:37 UTC
    I think you're asking how to overload stringification.
    use strict; use warnings; BEGIN { package MyPackage; use overload '""' => \&to_string; sub new { my $this = shift; my $class = ref($this) || $this; return bless {}, $class; } sub to_string { my ($self) = @_; return "ook?"; } } my $object = MyPackage->new(); print($object, "\n"); # ook?
Re: Anonymous Autoloading with OOP?
by Corion (Patriarch) on Oct 12, 2008 at 19:31 UTC

    All "methods" are called with the object as the first parameter:

    use Data::Dumper; ... sub AUTOLOAD { my $self = shift; warn $AUTOLOAD; warn Dumper \$self; };

    I didn't read the question completely - ikegami's reply is far more on the spot