blindluke has asked for the wisdom of the Perl Monks concerning the following question:

Is there a good way of making all the object attributes readonly in Moo? Something that would allow me to replace:

package Foo { use Moo; has 'attr_A' => ( is => 'ro', default => sub { 'A' } ); has 'attr_B' => ( is => 'ro', default => sub { 'B' } ); has 'attr_C' => ( is => 'ro', isa => sub { die unless $_[0] > 0 } +); }

With something like:

package Foo { use Moo; # this is where the magic happens has 'attr_A' => ( default => sub { 'A' } ); has 'attr_B' => ( default => sub { 'B' } ); has 'attr_C' => ( isa => sub { die unless $_[0] > 0 } ); }

There is an interesting blog post by mascip, about the possibility of enabling immutability for all the objects of a given class. The post refers to Moose, and its author seems to ask about a stronger restriction - making the object truly immutable. I'm only looking for some way to make the  is => 'ro' a default for all the attributes of a given class. Still, I wanted to link this post here since it provides a good explanation for the reasoning behind my question.

One 'bad way' I can think of would be using Filter::Simple, but I hope to find another way to do it. Humbly seeking your advice.

- Luke

Replies are listed 'Best First'.
Re: Making 'all' the attributes read only by default (Moo)
by BrowserUk (Patriarch) on Jan 22, 2015 at 22:02 UTC

    An immutable object is like waterproof paper towels; a leakproof sieve; or a docile guard dog.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      It's a good thing, then, that I'm not trying to make my objects immutable :)

      I'm just searching for some way to type is => 'ro' less, and make it clear that all the attributes of a given package have the 'ro' property set.

      - Luke

        Save yourself some typing and some angst:

        use constant Boo => { attr_A => 'A', attr_B => 'B', attr_C => 123, };

        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
        In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
        If all the attributes are "ro", then how is the resulting object not immutable (interface-wise at least)?