Lexical::Persistence(3)User Contributed Perl DocumentatioLnexical::Persistence(3)
NNAAMMEE
Lexical::Persistence - Persistent lexical variable values for arbitrary
calls.
SSYYNNOOPPSSIISS
#!/usr/bin/perl
use Lexical::Persistence;
my $persistence = Lexical::Persistence->new();
foreach my $number (qw(one two three four five)) {
$persistence->call(\&target, number => $number);
}
exit;
sub target {
my $arg_number; # Argument.
my $narf_x++; # Persistent.
my $_i++; # Dynamic.
my $j++; # Persistent.
print "arg_number = $arg_number\n";
print "\tnarf_x = $narf_x\n";
print "\t_i = $_i\n";
print "\tj = $j\n";
}
DDEESSCCRRIIPPTTIIOONN
Lexical::Persistence does a few things, all related. Note that all the
behaviors listed here are the defaults. Subclasses can override nearly
every aspect of Lexical::Persistence's behavior.
Lexical::Persistence lets your code access persistent data through
lexical variables. This example prints "some value" because the value
of $x perists in the $lp object between se_t_t_e_r_(_) and ge_t_t_e_r_(_).
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->call(\&setter);
$lp->call(\&getter);
sub setter { my $x = "some value" }
sub getter { print my $x, "\n" }
Lexicals with leading underscores are not persistent.
By default, Lexical::Persistence supports accessing data from multiple
sources through the use of variable prefixes. The se_t___c_o_n_t_e_x_t_(_) member
sets each data source. It takes a prefix name and a hash of key/value
pairs. By default, the keys must have sigils representing their
variable types.
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->set_context( pi => { '$member' => 3.141 } );
$lp->set_context( e => { '@member' => [ 2, '.', 7, 1, 8 ] } );
$lp->set_context(
animal => {
'%member' => { cat => "meow", dog => "woof" }
}
);
$lp->call(\&display);
sub display {
my ($pi_member, @e_member, %animal_member);
print "pi = $pi_member\n";
print "e = @e_member\n";
while (my ($animal, $sound) = each %animal_member) {
print "The $animal goes... $sound!\n";
}
}
And the corresponding output:
pi = 3.141
e = 2 . 7 1 8
The cat goes... meow!
The dog goes... woof!
By default, ca_l_l_(_) takes a single subroutine reference and an optional
list of named arguments. The arguments will be passed directly to the
called subroutine, but Lexical::Persistence also makes the values
available from the "arg" prefix.
use Lexical::Persistence;
my %animals = (
snake => "hiss",
plane => "I'm Cartesian",
);
my $lp = Lexical::Persistence->new();
while (my ($animal, $sound) = each %animals) {
$lp->call(\&display, animal => $animal, sound => $sound);
}
sub display {
my ($arg_animal, $arg_sound);
print "The $arg_animal goes... $arg_sound!\n";
}
And the corresponding output:
The plane goes... I'm Cartesian!
The snake goes... hiss!
Sometimes you want to call functions normally. The wr_a_p_(_) method will
wrap your function in a small thunk that does the ca_l_l_(_) for you,
returning a coderef.
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
my $thunk = $lp->wrap(\&display);
$thunk->(animal => "squirrel", sound => "nuts");
sub display {
my ($arg_animal, $arg_sound);
print "The $arg_animal goes... $arg_sound!\n";
}
And the corresponding output:
The squirrel goes... nuts!
Prefixes are the characters leading up to the first underscore in a
lexical variable's name. However, there's also a default context named
underscore. It's literally "_" because the underscore is not legal in
a context name by default. Variables without prefixes, or with
prefixes that have not been previously defined by se_t___c_o_n_t_e_x_t_(_), are
stored in that context.
The ge_t___c_o_n_t_e_x_t_(_) member returns a hash for a named context. This
allows your code to manipulate the values within a persistent context.
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->set_context(
_ => {
'@mind' => [qw(My mind is going. I can feel it.)]
}
);
while (1) {
$lp->call(\&display);
my $mind = $lp->get_context("_")->{'@mind'};
splice @$mind, rand(@$mind), 1;
last unless @$mind;
}
sub display {
my @mind;
print "@mind\n";
}
Displays something like:
My mind is going. I can feel it.
My is going. I can feel it.
My is going. I feel it.
My going. I feel it.
My going. I feel
My I feel
My I
My
It's possible to create multiple Lexical::Persistence objects, each
with a unique state.
use Lexical::Persistence;
my $lp_1 = Lexical::Persistence->new();
$lp_1->set_context( _ => { '$foo' => "context 1's foo" } );
my $lp_2 = Lexical::Persistence->new();
$lp_2->set_context( _ => { '$foo' => "the foo in context 2" } );
$lp_1->call(\&display);
$lp_2->call(\&display);
sub display {
print my $foo, "\n";
}
Gets you this output:
context 1's foo
the foo in context 2
You can also compile and execute perl code contained in plain strings
in a a lexical environment that already contains the persisted
variables.
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->do( 'my $message = "Hello, world" );
$lp->do( 'print "$message\n"' );
Which gives the output:
Hello, world
If you come up with other fun uses, let us know.
nneeww
Create a new lexical persistence object. This object will store one or
more persistent contexts. When called by this object, lexical
variables will take on the values kept in this object.
iinniittiiaalliizzee__ccoonntteexxttss
This method is called by ne_w_() to declare the initial contexts for a
new Lexical::Persistence object. The default implementation declares
the default "" context.
Override or extend it to create others as needed.
sseett__ccoonntteexxtt NNAAMMEE,, HHAASSHH
Store a context HASH within the persistence object, keyed on a NAME.
Members of the context HASH are unprefixed versions of the lexicals
they'll persist, including the sigil. For example, this se_t___c_o_n_t_e_x_t_()
call declares a "request" context with predefined values for three
variables: $requestfoo, @request_foo, and %request_foo:
$lp->set_context(
request => {
'$foo' => 'value of $request_foo',
'@foo' => [qw( value of @request_foo )],
'%foo' => { key => 'value of $request_foo{key}' }
}
);
See pa_r_s_e___v_a_r_i_a_b_l_e_(_) for information about how Lexical::Persistence
decides which context a lexical belongs to and how you can change that.
ggeett__ccoonntteexxtt NNAAMMEE
Returns a context hash associated with a particular context name.
Autovivifies the context if it doesn't already exist, so be careful
there.
ccaallll CCOODDEERREEFF,, AARRGGUUMMEENNTT__LLIISSTT
Call CODEREF with lexical persistence and an optional ARGUMENT_LIST,
consisting of name => value pairs. Unlike with se_t___c_o_n_t_e_x_t_(_), however,
argument names do not need sigils. This may change in the future,
however, as it's easy to access an argument with the wrong variable
type.
The ARGUMENT_LIST is passed to the called CODEREF through @ in the
usual way. They're also available as $argname variables for
convenience.
See pu_s_h___a_r_g___c_o_n_t_e_x_t_() for information about how $argname works, and
what you can do to change that behavior.
iinnvvookkee OOBBJJEECCTT,, MMEETTHHOODD,, AARRGGUUMMEENNTT__LLIISSTT
Invoke OBJECT->METHOD(ARGUMENT_LIST) while maintaining state for the
METHOD's lexical variables. Written in terms of ca_l_l_(_), except that it
takes OBJECT and METHOD rather than CODEREF. See ca_l_l_(_) for more
details.
May have issues with methods invoked via AUTOLOAD, as in_v_o_k_e_(_) uses
ca_n_(_) to find the method's CODEREF for ca_l_l_(_).
wwrraapp CCOODDEERREEFF
Wrap a function or anonymous CODEREF so that it's transparently called
via ca_l_l_(). Returns a coderef which can be called directly. Named
arguments to the call will automatically become available as $argname
lexicals within the called CODEREF.
See ca_l_l_(_) and pu_s_h___a_r_g___c_o_n_t_e_x_t_(_) for more details.
pprreeppaarree CCOODDEE
Wrap a CODE string in a subroutine definition, and prepend declarations
for all the variables stored in the Lexical::Persistence default
context. This avoids having to declare variables explicitly in the
code using 'my'. Returns a new code string ready for Perl's built-in
ev_a_l_(). From there, a program may $lp->c_a_l_l_() the code or $lp->w_r_a_p_(_)
it.
Also see "co_m_p_i_l_e_(_)", which is a convenient wrapper for pr_e_p_a_r_e_(_) and
Perl's built-in ev_a_l_(_).
Also see "do_(_)", which is a convenient way to pr_e_p_a_r_e_(_), ev_a_l_(_) and
ca_l_l_(_) in one step.
ccoommppiillee CCOODDEE
co_m_p_i_l_e_(_) is a convenience method to pr_e_p_a_r_e_(_) a CODE string, ev_a_l_(_)
it, and then return the resulting coderef. If it fails, it returns
false, and $@ will explain why.
ddoo CCOODDEE
do_(_) is a convenience method to co_m_p_i_l_e_(_) a CODE string and execute it.
It returns the result of CODE's execution, or it throws an exception on
failure.
This example prints the numbers 1 through 10. Note, however, that do_(_)
compiles the same code each time.
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->do('my $count = 0');
$lp->do('print ++$count, "\\n"') for 1..10;
Lexical declarations are preserved across do_(_) invocations, such as
with $count in the surrounding examples. This behavior is part of
pr_e_p_a_r_e_(_), which do_(_) uses via co_m_p_i_l_e_(_).
The previous example may be rewritten in terms of co_m_p_i_l_e_(_) and ca_l_l_(_)
to avoid recompiling code every iteration. Lexical declarations are
preserved between do_(_) and co_m_p_i_l_e_(_) as well:
use Lexical::Persistence;
my $lp = Lexical::Persistence->new();
$lp->do('my $count = 0');
my $coderef = $lp->compile('print ++$count, "\\n"');
$lp->call($coderef) for 1..10;
do_(_) inherits some limitations from PadWalker's pe_e_k___s_u_b_(_). For
instance, it cannot alias lexicals within su_b_(_) definitions in the
supplied CODE string. However, Lexical::Persistence can do this with
careful use of ev_a_l_(_) and some custom CODE preparation.
ppaarrssee_vvaarriiaabbllee VVAARRIIAABBLLEE_NNAAMMEE
This method determines whether VARIABLE_NAME should be persistent. If
it should, pa_r_s_e___v_a_r_i_a_b_l_e_(_) will return three values: the variable's
sigil ('$', '@' or '%'), the context name in which the variable
persists (see se_t___c_o_n_t_e_x_t_(_)), and the name of the member within that
context where the value is stored. pa_r_s_e___v_a_r_i_a_b_l_e_() returns nothing if
VARIABLENAME should not be persistent.
pa_r_s_e___v_a_r_i_a_b_l_e_(_) also determines whether the member name includes its
sigil. By default, the "arg" context is the only one with members that
have no sigils. This is done to support the unadorned argument names
used by ca_l_l_(_).
This method implements a default behavior. It's intended to be
overridden or extended by subclasses.
ggeett_mmeemmbbeerr_rreeff SSIIGGIILL,, CCOONNTTEEXXTT,, MMEEMMBBEERR
This method fetches a reference to the named MEMBER of a particular
named CONTEXT. The returned value type will be governed by the given
SIGIL.
Scalar values are stored internally as scalars to be consistent with
how most people store scalars.
The persistent value is created if it doesn't exist. The initial value
is undef or empty, depending on its type.
This method implements a default behavior. It's intended to be
overridden or extended by subclasses.
ppuusshh_aarrggccoonntteexxtt AARRGGUUMMEENNTT_LLIISSTT
Convert a named ARGUMENT_LIST into members of an argument context, and
call se_t___c_o_n_t_e_x_t_() to declare that context. This is how $argfoo
variables are supported. This method returns the previous context,
fetched by ge_t___c_o_n_t_e_x_t_(_) before the new context is set.
This method implements a default behavior. It's intended to be
overridden or extended by subclasses. For example, to redefine the
parameters as $param_foo.
See po_p___a_r_g___c_o_n_t_e_x_t_(_) for the other side of this coin.
ppoopp_aarrggccoonntteexxtt OOLLDDAARRGG_CCOONNTTEEXXTT
Restores OLD_ARG_CONTEXT after a target function has returned. The
OLD_ARG_CONTEXT is the return value from the pu_s_h___a_r_g___c_o_n_t_e_x_t_(_) call
just prior to the target function's call.
This method implements a default behavior. It's intended to be
overridden or extended by subclasses.
SSEEEE AALLSSOO
POE::Stage, Devel::LexAlias, PadWalker, Catalyst::Controller::BindLex.
BBUUGG TTRRAACCKKEERR
https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Lexical-Persistence
RREEPPOOSSIITTOORRYY
http://github.com/rcaputo/lexical-persistence
http://gitorious.org/lexical-persistence
OOTTHHEERR RREESSOOUURRCCEESS
http://search.cpan.org/dist/Lexical-Persistence/
CCOOPPYYRRIIGGHHTT
Lexical::Persistence in copyright 2006-2010 by Rocco Caputo. All
rights reserved. Lexical::Persistence is free software. It is
released under the same terms as Perl itself.
AACCKKNNOOWWLLEEDDGGEEMMEENNTTSS
Thanks to Matt Trout and Yuval Kogman for lots of inspiration. They
were the demon and the other demon sitting on my shoulders.
Nick Perez convinced me to make this a class rather than persist with
the original, functional design. While Higher Order Perl is fun for
development, I have to say the move to OO was a good one.
Paul "LeoNerd" Evans contributed the co_m_p_i_l_e_(_) and ev_a_l_(_) methods.
The South Florida Perl Mongers, especially Jeff Bisbee and Marlon
Bailey, for documentation feedback.
irc://irc.perl.org/poe for support and feedback.
perl v5.10.0 2010-03-08 Lexical::Persistence(3)