in reply to Re: overloading '0+'
in thread overloading '0+'

So if we add function to handle the conversion to an integer there should be one call to truncate and other call to the overload integer function.
#!/usr/bin/env perl # use strict; use warnings; package Soldier; use overload '0+' => \&truncate, 'int' => \&my_int; my $soldier1 = { NAME => 'BENJAMIN', RANK => 'PRIVATE', SERIAL => 151.11 }; bless $soldier1; print int($soldier1), "\n"; sub truncate { print "sub truncate called: ", $_[0]->{SERIAL}, "\n"; return $_[0]->{SERIAL}; } sub my_int { print "sub my_int called: ", $_[0]->{SERIAL}, "\n"; return int($_[0]->{SERIAL}); }
Produces the (unexpected) output;
sub my_int called: 151.11 151
Thoughts?

Replies are listed 'Best First'.
Re^3: overloading '0+'
by CountZero (Bishop) on Sep 03, 2007 at 09:11 UTC
    Your my_int-routine does not require its argument to be numified as it works directly on the object.

    If you force the object to be numified by changing the argument of int to: $soldier1 + 0 (you will have to overload '+' or add fallback => 1 to the overload hash) you will see truncate being called.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James