Don't ask to ask, just ask | |
PerlMonks |
Real private methods using lexical subs in Perl 5.18.by tobyink (Canon) |
on May 31, 2013 at 11:58 UTC ( [id://1036238]=perlmeditation: print w/replies, xml ) | Need Help?? |
Perlers tend to use the convention of using a leading underscore to mark private/protected methods in OO code. However, this has some problems:
Perl 5.18's experimental lexical subs feature can be exploited to create truly private subs. We need to introduce a little syntactic sugar (or perhaps vinegar, depending on how you look at it), to circumvent the fact that lexical subs are not really designed to be called as methods - we use this syntax: $self->${\\&method_name}(@args). (Think of it as a mega-sigil.)
Update: I hasten to add that I'm not advocating doing this in production code any time in the near future. But it's an interesting option to think about in years to come. I'll also point out that a similar thing can be achieved using coderefs in earlier versions of Perl:
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Back to
Meditations
|
|