Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to string overload on a Moose attribute accessor?

Tags:

perl

moose

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:

  1. Marking id is => bare, and replacing it with my own accessor: sub id {$_[0]->{id}}. But this is just a hack.

  2. 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?

like image 697
stevenl Avatar asked Aug 29 '11 12:08

stevenl


2 Answers

use overload '""' => sub {shift->id}, fallback => 1;

Works fine for me.

like image 127
Hynek -Pichi- Vychodil Avatar answered Oct 14 '22 00:10

Hynek -Pichi- Vychodil


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.

like image 5
Ven'Tatsu Avatar answered Oct 13 '22 23:10

Ven'Tatsu