views:

127

answers:

2

I saw some code that called methods on scalars (numbers), something like:

print 42->is_odd

What do you have to overload so that you can achieve this sort of "functionality" in your code?

+10  A: 

Are you referring to autobox? See also http://stackoverflow.com/questions/1521563/should-i-use-autobox-in-perl.

Ether
it's one module I noticed. another one could be `scalar::object`. I saw that `autoload` uses XS, and I noticed `scalar::object` doesn't. I'd rather be more interested in the way `scalar::object` does it's thing. I'm curious if this can be done without resorting to lower level programming.
Geo
`scalar::object` uses `overload::constant` and other `overload` magic, but it also doesn't have nearly the power `autobox` does. `autobox` works by hooking into the implementation of the `->foo()` method call operator itself.
hobbs
autobox certainly is the way to go for this kind of functionality.
tsee
+1  A: 

This is an example using the autobox feature.

#!/usr/bin/perl

use strict;
use warnings;

package MyInt;

sub is_odd {
  my $int = shift;
  return ($int%2);
}

package main;

use autobox INTEGER => 'MyInt';
print "42: ".42->is_odd."\n";
print "43: ".43->is_odd."\n";
print "44: ".44->is_odd."\n";
Bluegene