Perl - calling an instance of a class

Is there a way to catch the event of calling an instance of the Perl class?

my $obj = ExampleClass->new(); $obj(); # do something without producing error 

I would like to be able to handle this from a class / module definition. Something similar to the __call__ method in Python or the __call __call in Lua.

+5
source share
2 answers

I'm still not sure what the use case is, but you can overload class to handle code dereferencing.

 package ExampleClass; use overload '&{}' => \&__call__; # Or an anon sub. sub new { bless {@_}, shift; } sub __call__ { sub { warn "calling an instance event" }; } package main; my $obj = ExampleClass->new; $obj->(); &$obj(); # same as $obj->() 

Typical Output:

 $ perl 44956235.pl calling an instance event at 44956235.pl line 7. calling an instance event at 44956235.pl line 7. 
+7
source

Overloading " &{} " is obviously the way out, but you could create your object on a sub, instead of a common hash.

ExampleClass.pm :

 package ExampleClass; use strict; use warnings; use feature qw( current_sub say ); my %objects; sub new { my $class = shift; my $dummy; # Force each evaluation of sub{} to return a new variable. my $self = bless(sub { $dummy if 0; __SUB__ ->__call__(@_) }, $class) }, $class); my $inner = $objects{$self} = {}; return $self; } sub DESTROY { my $self = shift; delete($objects{$self}); } sub __call__ { my $inner = $objects{ my $self = shift }; say "__call__(".join(", ", @_).")"; } sub some_attribute { my $inner = $objects{ my $self = shift }; if (@_) { $inner->{some_attribute} = $_[0]; } return $inner->{some_attribute}; } 1; 

The main program:

 #!/usr/bin/perl use strict; use warnings; use feature qw( say ); use ExampleClass qw( ); { my $obj = ExampleClass->new(); $obj->some_attribute("value"); say $obj->some_attribute(); $obj->(qw( abc )); } { my $obj1 = ExampleClass->new(); $obj1->some_attribute("value1"); my $obj2 = ExampleClass->new(); $obj2->some_attribute("value2"); say $obj1->some_attribute(); say $obj2->some_attribute(); } 

Output:

 value __call__(a, b, c) value1 value2 

This is basically what is called an β€œinside out” object.

+5
source

Source: https://habr.com/ru/post/1269574/


All Articles