开发者

How can I call methods on Perl scalars?

I saw 开发者_C百科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?


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


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";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜