Ephemeral methods, or what to call 'dispatch to a variable containing a subref'?

In my last post, I use a Perl dispatch pattern where you store a subroutine reference in a variable and then use that as the method to call on an object. Like so:

my $method = sub { ... };
$invocant->$method(@args);

Is there a name for this pattern? If not I propose to call the “method” an “ephemeral method”. Does this work for everyone?

Note that you really can’t call it a lexical method for several reasons.

5 Comments

Personally I call it a lexical method.

Recent versions of Moops have facilities for lexical methods and lexical accessors. (Example.)

I wonder how this would relate to the return value of can(), and overloading can to return a method specialized to the instance that it was called on.

Actually, lexical subroutines can’t be called as methods…

use v5.18;
use feature 'lexical_subs';
no warnings 'experimental::lexical_subs';

package Foo { use Moo }
my sub xxx { say ref shift }

Foo->new->xxx;

… unless you jump through some serious hoops…

use v5.18;
use feature 'lexical_subs';
no warnings 'experimental::lexical_subs';

package Foo { use Moo }
my sub xxx { say ref shift }

Foo->new->${ \\&xxx };

Leave a comment

About Joel Berger

user-pic As I delve into the deeper Perl magic I like to share what I can.