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]


In reply to Overloading oddity by theguvnor

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.