what is the best way to string overload on a Moose attribute accessor?
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',
开发者_StackOverflow 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?
use overload '""' => sub {shift->id}, fallback => 1;
Works fine for me.
I believe you are getting an error because \&id
creates a placeholder for a sub to be defined later, because Perl will need to know the address that sub will have when it is defined to create a reference to it. Moose has it's own checks to try to avoid overwriting methods you define and reports this to you.
Since I think what you really want to do is call the id
method when the object is used as a sting like so:
use overload '""' => 'id', fallback => 1;
From the overload
documentation
Values specified as strings are interpreted as method names.
精彩评论