4

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?

Svante
  • 50,694
  • 11
  • 78
  • 122
Geo
  • 93,257
  • 117
  • 344
  • 520

2 Answers2

10

Are you referring to autobox? See also Should I use autobox in Perl?.

Community
  • 1
  • 1
Ether
  • 53,118
  • 13
  • 86
  • 159
  • 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 Nov 25 '09 at 22:00
  • 3
    `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 Nov 25 '09 at 22:19
  • autobox certainly is the way to go for this kind of functionality. – tsee Nov 26 '09 at 09:06
1

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";
Simon
  • 1,643
  • 2
  • 17
  • 23