in reply to Re^3: OOP - Constant Vs. Subroutine
in thread OOP - Constant Vs. Subroutine

You can achieve the same effect as Readonly for hashes, without the overhead, using Hash::Util:

#! perl -slw use strict; use Hash::Util qw[ lock_hash ]; use constant FOO => { x => 0 }; lock_hash( %{ FOO() } ); ++ FOO->{x}; print FOO->{x}; __END__ C:\test>junk7 Modification of a read-only value attempted at C:\test\junk7.pl line 7 +.

It would be a nice addition to constant if it would (or could be instructed to) do that for you.

Internals::SetReadOnly(), also works to an extent on both hashes and arrays:

#! perl -slw use strict; use Internals qw[ SetReadOnly ]; use constant BAR => { x => 1 }; SetReadOnly( BAR ); BAR->{y} = 12345; ## Modification of a read-only value attempted ... use constant BAZ => [ 1, 2, 3, 4, 5, ]; SetReadOnly( BAZ ); push @{ +BAZ }, 1; # Modification of a read-only value attempted ... ## Unfortunately, these do not produce errors? ++BAR->{x}; ++BAZ->[0]; __END__ C:\test>junk7 Modification of a read-only value attempted at C:\test\junk7.pl line 1 +3.

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".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^5: OOP - Constant Vs. Subroutine
by diotalevi (Canon) on May 13, 2007 at 07:38 UTC

    I frequently have constant data structures. Having to loop over all the data in my constant just to set the readonly flag sucks and mostly I don't do it. I'd really just wish for constant.pm to learn to do the right thing. I suppose I should just go patch it.

    ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊