I have a class where I want to apply string overloading on its id
attribute. However, Moose doesn't allow string overloading on attribute accessors. For example:
package Foo;
use Moose;
use overload '""' => \&id, fallback => 1;
has 'id' => (
is => 'ro',
isa => 'Int',
default => 5,
);
package main;
my $foo = Foo->new;
print "$foo\n";
The above will give an error:
You are overwriting a locally defined method (id) with an accessor at C:/perl/site/lib/Moose/Meta/Attribute.pm line 927
I have tried a couple of options to get around this:
Marking
id
is => bare
, and replacing it with my own accessor:sub id {$_[0]->{id}}
. But this is just a hack.Having the string overloader use another method which just delegates back to id:
sub to_string {$_[0]->id}
.
I'm just wondering if anyone has a better way of doing this?