[Israel.pm] object oriented anonymous autoloading?

Gabor Szabo szabgab at gmail.com
Sun Oct 12 13:08:26 PDT 2008


On Sun, Oct 12, 2008 at 9:51 PM, Ronen Angluster <beerholder at gmail.com> wrote:
> Hi all!
> the subject is actually drawn from a lack of better understanding in
> this particular topic...
> given this code:
> package MyPackge;
> sub new {
> my $this = shift;
> .
> .
> .
> blabla
> ..
> .
> bless $self;
> return $self
> }
> and if i run:
> my $object = MyPackage->new();
> is there a way to "autoload" the object so that if i "print $object"
> the object will return a given value(or a subroutine that will return
> a value)
> instead of its own ref & memory address ?
> i tried using AUTOLOAD (which works great for missing methods and
> such) but it seems that since i don't try to activate any method
> on the object, perl just return the value of the object, i.e: its reference.
> Thanks in advance,


What you are looking for is to overload the stringification method of
your object.
At least that's how it is called in Perlish.
You can do that using the following example:


#!/usr/bin/perl
use strict;
use warnings;


my $z = X->new;
print $z, "\n";

package X;
use strict;
use warnings;

use overload
	'""' => \&f,
;

sub new {
	return bless {}, shift;
}

sub f {
	return time;
}


====================
That is you need to define what method is called (in the above case
the f() method
when the string version of the object is requested.

====================

For more detailed explanation see http://perldoc.perl.org/overload.html

Two notes regarding your question though
1) please make sure you always use the 2 param version of bless
    (see http://perldoc.perl.org/functions/bless.html ) or you risk breaking
    subclassing.
2) Please indent your examples even when you send to the mailing list
    to make it easier for us to read.

regards
   Gabor

-- 
Gabor Szabo                     http://szabgab.com/blog.html
Perl Training in Israel         http://www.pti.co.il/
Test Automation Tips        http://szabgab.com/test_automation_tips.html



More information about the Perl mailing list