Gabor's example of overloading was: > use overload > '""' => \&f, > ;
Gabor then noted: > 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. Gabor, I am no expert in overloading, so correct me if I'm wrong here: Doesn't your example of overloading break inheritance? Don't you have to use "f" as the value rather than referencing \&f directly in order for subclasses to be able to define their own "f" method to provide subclass-specific overloading? Won't all subclasses (wrongly) call X::f in your example? --edan -----Original Message----- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Gabor Szabo Sent: Sunday, October 12, 2008 22:08 To: Perl in Israel Subject: Re: [Israel.pm] object oriented anonymous autoloading? On Sun, Oct 12, 2008 at 9:51 PM, Ronen Angluster <[EMAIL PROTECTED]> 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 _______________________________________________ Perl mailing list [email protected] http://perl.org.il/mailman/listinfo/perl _______________________________________________ Perl mailing list [email protected] http://perl.org.il/mailman/listinfo/perl
