Hi

I'm trying to work out how/why one might overload '0+' ... and I'm not having much success.
use warnings; use strict; package Soldier; use overload '0+' => \&truncate; my $soldier1 = {NAME => 'BENJAMIN', RANK => 'PRIVATE' , SERIAL => 151.11}; bless $soldier1; my $int = int($soldier1); print $int, "\n"; sub truncate { print "sub truncate called: ", int($_[0]->{SERIAL}), "\n"; return int($_[0]->{SERIAL}); } __END__ OUTPUTS: sub truncate called: 151 sub truncate called: 151 151
Questions:
1) Why does the sub truncate get called twice ?
2) Why would one want to overload the int() function with use overload '0+' => \&truncate; when use overload 'int' => \&truncate; works just as well (and gets called only once when substituted into the above demo script) ?
3) I notice that $soldier1 ? 1 : 0; also calls truncate (just once). I don't know why that is. Under what other circumstances will sub truncate be called ?

Perhaps I just need to see a proper example of the usage of overloading '0+'.

Cheers,
Rob

In reply to overloading '0+' by syphilis

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.