I would like to have immutable attributes in Moose. 'ro' takes care of this for scalar values and references, however, the inner workings of the reference are not affected by this write protection. This being Perl, there must be a way around this …
package SomeClass;
use Moose;
has 'list' => (
is => 'ro',
isa => 'ArrayRef',
);
package main;
use warnings; use strict;
use v5.36;
use feature qw(try);
no warnings qw(experimental::try);
use Data::Printer;
my $x = SomeClass->new({
list => [qw(a b c)]
});
# how do I disallow this?
push $x->list()->@*, 'd';
p $x;
#list [
# [0] "a",
# [1] "b",
# [2] "c",
# [3] "d"
# ]
But I'd like a behavior akin to:
use Const::Fast;
const my $LIST => [qw(x y z)];
try {
push $LIST->@*, 'no way';
} catch ($e) {
warn $e;
}
# Modification of a read-only value attempted at ... line ...
# [
# [0] "x" (read-only),
# [1] "y" (read-only),
# [2] "z" (read-only)
# ] (read-only) (read-only)
p $LIST;