Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Immutable object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Perl === In [[Perl]], one can create an immutable class with the Moo library by simply declaring all the attributes read only: <syntaxhighlight lang="perl"> package Immutable; use Moo; has value => ( is => 'ro', # read only default => 'data', # can be overridden by supplying the constructor with # a value: Immutable->new(value => 'something else'); ); 1; </syntaxhighlight> Creating an immutable class used to require two steps: first, creating accessors (either automatically or manually) that prevent modification of object attributes, and secondly, preventing direct modification of the instance data of instances of that class (this was usually stored in a hash reference, and could be locked with Hash::Util's lock_hash function): <syntaxhighlight lang="perl"> package Immutable; use strict; use warnings; use base qw(Class::Accessor); # create read-only accessors __PACKAGE__->mk_ro_accessors(qw(value)); use Hash::Util 'lock_hash'; sub new { my $class = shift; return $class if ref($class); die "Arguments to new must be key => value pairs\n" unless (@_ % 2 == 0); my %defaults = ( value => 'data', ); my $obj = { %defaults, @_, }; bless $obj, $class; # prevent modification of the object data lock_hash %$obj; } 1; </syntaxhighlight> Or, with a manually written accessor: <syntaxhighlight lang="perl"> package Immutable; use strict; use warnings; use Hash::Util 'lock_hash'; sub new { my $class = shift; return $class if ref($class); die "Arguments to new must be key => value pairs\n" unless (@_ % 2 == 0); my %defaults = ( value => 'data', ); my $obj = { %defaults, @_, }; bless $obj, $class; # prevent modification of the object data lock_hash %$obj; } # read-only accessor sub value { my $self = shift; if (my $new_value = shift) { # trying to set a new value die "This object cannot be modified\n"; } else { return $self->{value} } } 1; </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)