theguvnor has asked for the wisdom of the Perl Monks concerning the following question:
Today I found something interesting. I've used overloading in the past without trouble but today wasn't getting stringification to work. I reduced my problem to the following test case:
package SomeClass; use overload '""'=>"name"; sub new { return bless {}, shift; } sub name { my $self = shift; $self->{NAME} = shift if @_; return $self->{NAME}; } 1;
And here's my test script to use the class above:
use lib '.'; use SomeClass; my $thing = SomeClass->new; $thing->name('TestObj'); print "Explicit: my name is ", $thing->name, "\n"; print "Implicit: my name is $thing\n"; exit;
The second print statement printed "Implicit: my name is " whereas the first print worked as desired, including the name.
I tested the above under both 5.8.0 Linux-multi-thread and 5.8.0 MSWin-multi-thread and eventually came to realize that I could get it to work by pointing my overload directive to a third function in SomeClass:
sub stringify { my $self = shift; return $self->{NAME}; }
Any ideas why my first attempt failed? I can't see any good reason why my stringify() method works but not name(). Thanks in advance.
[Jon]
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Overloading oddity
by BrowserUk (Patriarch) on Jan 27, 2004 at 22:33 UTC | |
by theguvnor (Chaplain) on Jan 27, 2004 at 23:01 UTC | |
|
Re: Overloading oddity
by Ovid (Cardinal) on Jan 27, 2004 at 21:59 UTC | |
by Abigail-II (Bishop) on Jan 27, 2004 at 23:13 UTC | |
by theguvnor (Chaplain) on Jan 27, 2004 at 22:12 UTC | |
|
Re: Overloading oddity
by ysth (Canon) on Jan 27, 2004 at 23:01 UTC | |
|
Re: Overloading oddity
by dragonchild (Archbishop) on Jan 28, 2004 at 03:56 UTC | |
by theguvnor (Chaplain) on Jan 28, 2004 at 14:47 UTC |