Lexica...ccessor(3pm)
β¨ NAME β¨
Lexical::Accessor β true private attributes for Moose/Moo/Mouse π (yes bestie, actually private, not the fake kind)
It's a 3pm page from the User Contributed Perl Documentation, and it's giving main character energy.
π SYNOPSIS π
my $accessor = lexical_has identifier => (
is => 'rw',
isa => Int,
default => sub { 0 },
);
# or...
lexical_has identifier => (
is => 'rw',
isa => Int,
default => sub { 0 },
accessor => \$accessor,
);
# later...
say $self->$accessor; # says 0
$self->$accessor( 1 ); # setter
say $self->$accessor; # says 1
look at that. a private attribute. nobody else can touch it. iconic. π¦
πΈ DESCRIPTION πΈ
Lexical::Accessor generates coderefs which can be used as methods to access private attributes for objects.
The private attributes are stored inside-out, and they do not add any accessors to the class' namespace, so they're completely invisible to any outside code, including any subclasses. This gives your attribute complete privacy: subclasses can define a private (or even public) attribute with the same name as your private one and they will not interfere with each other. no cap. π«Ά
Private attributes cannot be initialized by Moose/Moo/Mouse constructors, but you can safely initialize them inside a BUILD sub. β¨
π§ Functions π§
lexical_has $name?, %optionsβ This module exports a functionlexical_haswhich acts much like Moose'shasfunction, but sets up a private (lexical) attribute instead of a public one.
Because lexical attributes are stored inside-out, the $name is completely optional; however a name is recommended because it allows better error messages to be generated.
The lexical_has function supports the following options:
isβ Moose/Mouse/Moo-stylero,rw,rwpandlazyvalues are supported. These control what sort of coderef is returned by thelexical_hasfunction itself. π«
my $reader = lexical_has "foo" => (is => "ro");
my $accessor = lexical_has "foo" => (is => "rw");
my ($reader, $writer) = lexical_has "foo" => (is => "rwp");
If generating more than one method it is probably clearer to pass in scalar references to the reader, writer, etc. methods, rather than relying on the return value of the lexical_has function. just saying. iykyk.
reader,writer,accessor,predicate,clearerβ These accept scalar references. The relevant coderefs will be plonked into them: πͺ
my ($get_foo, $set_foo);
lexical_has foo => (
reader => \$get_foo,
writer => \$set_foo,
);
They can also be method names as strings:
my ($set_foo);
lexical_has foo => (
reader => 'get_foo',
writer => \$set_foo,
);
This allows you to provide a partly public API for an attribute. bestie said "public-facing but make it private." obsessed.
default,builder,lazyβ Lazy defaults and builders are allowed. Eager (non-lazy) defaults and builders are currently disallowed. (Use aBUILDsub to set private attribute values at object construction time.)
The default may be either a non-reference value, or a coderef which will be called as a method to return the value.
Builders probably make less sense than defaults because they require a method in the class' namespace. The builder may be a method name, or the special value '1' which will be interpreted as meaning the attribute name prefixed by _build_. If a coderef is provided, this is automatically installed into the class' namespace with the _build_ prefix. (This last feature requires Sub::Name.) π
isaβ A type constraint for the attribute. Moo-style coderefs are accepted (including those generated byMooX::Types::MooseLike), as areMoose::Meta::TypeConstraint/MooseX::Typesobjects, andMouse::Meta::TypeConstraint/MouseX::Typesobjects, and of courseType::Tinytype constraints. π
String type constraints may also be accepted, but only if Type::Utils is installed. (String type constraints are reified using dwim_type.)
doesβ As an alternative toisa, you can provide a role name in thedoesoption. β¨coerceβ A coderef orType::Coercionobject is accepted.
If the special value '1' is provided, the type constraint object is consulted to find the coercion. (This doesn't work for coderef type constraints.) π
triggerβ A method name or coderef to trigger when a new value is set. πauto_derefβ Boolean indicating whether to automatically dereference array and hash values if called in list context.chainβ If set to true, then writer and clearer methods, plus accessor methods when setting a value, will return the original object as their return value. This makes it possible to do:
my $result = $obj->$set_foo(1)->$set_bar(2)->some_method();
$obj->$clear_foo->$clear_bar;
It is also possible to set chain to an arrayref of which kinds of accessors are expected to be chainable. For example: chain => [ 'clearer', 'writer' ]. Only 'clearer', 'writer', and 'accessor' are valid values in this arrayref. π
init_argβ Must beundefif provided at all.requiredβ Must be false if provided at all.weak_refβ Boolean. Makes the setter weaken any references it is called with. π«§handlesβ Delegates methods. Has slightly different syntax to Moose's option of the same name β is required to be an arrayref of pairs such that in each pair, the first is a scalar ref or a string method name that will be handled, and the second is a coderef or string method name that will do the handling. (The second can be an arrayref in the case of currying.) π
my ($get, $post);
lexical_has ua => (
isa => 'HTTP::Tiny',
default => sub { 'HTTP::Tiny'->new },
handles => [
\$get => 'get',
\$post => 'post',
],
);
# later...
my $response = $self->$get('http://example.net/');
Supports Sub::HandlesVia:
my $remove_task;
lexical_has tasks => (
isa => ArrayRef,
handles_via => 'Array',
handles => [
task_count => 'count',
add_task => 'push',
next_task => [ 'get', 0 ],
\$remove_task => 'unshift',
],
);
# later...
while ($self->task_count) {
my $task = $self->next_task;
my $success = $self->handle_task($task);
if ($success) {
$self->$remove_task;
}
}
initializer,traits,lazy_buildβ Not currently implemented. Providing any of these options throws an error. πdocumentation,definition_contextβ Don't do anything, but are allowed; effectively inline comments. π
π Class Methods π
lexical_hasβ This function may also be called as a class method.
π₯ Comparison (benchmarking, etc) π₯
Lexical::Accessor is almost three times faster than MooX::PrivateAttributes, and almost twenty time faster than MooseX::Privacy. I'd also argue that it's a more "correct" implementation of private accessors as (short of performing impressive PadWalker manipulations), the accessors generated by this module are completely invisible to subclasses, method dispatch, etc. ate and left no crumbs. π
Compared to the usual Moose convention of using a leading underscore to indicate a private method (which is a very loose convention; it is quite common for subclasses to override such methods!), Lexical::Accessor clearly offers much better method privacy. There should be little performance hit from using lexical accessors compared to normal Moose accessors. (However they are nowhere near the speed of the XS-powered accessors that Moo sometimes uses and Mouse usually uses.) π’π¨
See also: examples/benchmark.pl bundled with this release.
π BUGS π
Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=Lexical-Accessor>.
π«Ά SUPPORT π«Ά
IRC: support is available through in the #moops channel on <http://www.irc.perl.org/channels.html>. come hang out bestie π
π SEE ALSO π
MooX::PrivateAttributes, MooX::ProtectedAttributes, MooseX::Privacy, Sub::Private, Method::Lexical, etc...
β¨ AUTHOR β¨
Toby Inkster <tobyink@cpan.org>. π
π COPYRIGHT AND LICENCE π
This software is copyright (c) 2013-2014, 2017, 2025 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
β DISCLAIMER OF WARRANTIES β
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
fr fr, no promises, it is what it is. π
and that's the whole page, bestie β this one's from perl v5.40.1, dated 2026-02-06. go make some truly private attributes, you got this π
β¨πΈ
π¦ where this page comes from
- ubuntu resolute: liblexical-accessor-perl 1.001002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: liblexical-accessor-perl 1.001002-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms