How can I call methods on Perl scalars?
-
05-07-2019 - |
Question
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?
Solution
Are you referring to autobox? See also Should I use autobox in Perl?.
OTHER TIPS
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";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow