Skip to content

Instantly share code, notes, and snippets.

@preaction
Created January 10, 2020 17:28
Show Gist options
  • Save preaction/278860ea296d0c5a84f46b1e777491e2 to your computer and use it in GitHub Desktop.
Save preaction/278860ea296d0c5a84f46b1e777491e2 to your computer and use it in GitHub Desktop.
Forbid breaking encapsulation of an object
package Foo;
use overload '%{}' => sub {
my ( $package ) = caller;
if ( !$package->isa( __PACKAGE__ ) ) {
require Carp;
Carp::cluck( "Use a method instead!" );
}
return $_[0];
};
sub new { return bless { foo => 'bar' }, __PACKAGE__ }
sub foo { return shift->{foo} }
package main;
use v5.16;
my $foo = Foo->new;
say $foo->foo;
say $foo->{foo};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment