1Lexical::Persistence(3)User Contributed Perl DocumentatioLnexical::Persistence(3)
2
3
4

NAME

6       Lexical::Persistence - Persistent lexical variable values for arbitrary
7       calls.
8

SYNOPSIS

10               #!/usr/bin/perl
11
12               use Lexical::Persistence;
13
14               my $persistence = Lexical::Persistence->new();
15               foreach my $number (qw(one two three four five)) {
16                       $persistence->call(\&target, number => $number);
17               }
18
19               exit;
20
21               sub target {
22                       my $arg_number;   # Argument.
23                       my $narf_x++;     # Persistent.
24                       my $_i++;         # Dynamic.
25                       my $j++;          # Persistent.
26
27                       print "arg_number = $arg_number\n";
28                       print "\tnarf_x = $narf_x\n";
29                       print "\t_i = $_i\n";
30                       print "\tj = $j\n";
31               }
32

DESCRIPTION

34       Lexical::Persistence does a few things, all related.  Note that all the
35       behaviors listed here are the defaults.  Subclasses can override nearly
36       every aspect of Lexical::Persistence's behavior.
37
38       Lexical::Persistence lets your code access persistent data through
39       lexical variables.  This example prints "some value" because the value
40       of $x perists in the $lp object between setter() and getter().
41
42               use Lexical::Persistence;
43
44               my $lp = Lexical::Persistence->new();
45               $lp->call(\&setter);
46               $lp->call(\&getter);
47
48               sub setter { my $x = "some value" }
49               sub getter { print my $x, "\n" }
50
51       Lexicals with leading underscores are not persistent.
52
53       By default, Lexical::Persistence supports accessing data from multiple
54       sources through the use of variable prefixes.  The set_context() member
55       sets each data source.  It takes a prefix name and a hash of key/value
56       pairs.  By default, the keys must have sigils representing their
57       variable types.
58
59               use Lexical::Persistence;
60
61               my $lp = Lexical::Persistence->new();
62               $lp->set_context( pi => { '$member' => 3.141 } );
63               $lp->set_context( e => { '@member' => [ 2, '.', 7, 1, 8 ] } );
64               $lp->set_context(
65                       animal => {
66                               '%member' => { cat => "meow", dog => "woof" }
67                       }
68               );
69
70               $lp->call(\&display);
71
72               sub display {
73                       my ($pi_member, @e_member, %animal_member);
74
75                       print "pi = $pi_member\n";
76                       print "e = @e_member\n";
77                       while (my ($animal, $sound) = each %animal_member) {
78                               print "The $animal goes... $sound!\n";
79                       }
80               }
81
82       And the corresponding output:
83
84               pi = 3.141
85               e = 2 . 7 1 8
86               The cat goes... meow!
87               The dog goes... woof!
88
89       By default, call() takes a single subroutine reference and an optional
90       list of named arguments.  The arguments will be passed directly to the
91       called subroutine, but Lexical::Persistence also makes the values
92       available from the "arg" prefix.
93
94               use Lexical::Persistence;
95
96               my %animals = (
97                       snake => "hiss",
98                       plane => "I'm Cartesian",
99               );
100
101               my $lp = Lexical::Persistence->new();
102               while (my ($animal, $sound) = each %animals) {
103                       $lp->call(\&display, animal => $animal, sound => $sound);
104               }
105
106               sub display {
107                       my ($arg_animal, $arg_sound);
108                       print "The $arg_animal goes... $arg_sound!\n";
109               }
110
111       And the corresponding output:
112
113               The plane goes... I'm Cartesian!
114               The snake goes... hiss!
115
116       Sometimes you want to call functions normally.  The wrap() method will
117       wrap your function in a small thunk that does the call() for you,
118       returning a coderef.
119
120               use Lexical::Persistence;
121
122               my $lp = Lexical::Persistence->new();
123               my $thunk = $lp->wrap(\&display);
124
125               $thunk->(animal => "squirrel", sound => "nuts");
126
127               sub display {
128                       my ($arg_animal, $arg_sound);
129                       print "The $arg_animal goes... $arg_sound!\n";
130               }
131
132       And the corresponding output:
133
134               The squirrel goes... nuts!
135
136       Prefixes are the characters leading up to the first underscore in a
137       lexical variable's name.  However, there's also a default context named
138       underscore.  It's literally "_" because the underscore is not legal in
139       a context name by default.  Variables without prefixes, or with
140       prefixes that have not been previously defined by set_context(), are
141       stored in that context.
142
143       The get_context() member returns a hash for a named context.  This
144       allows your code to manipulate the values within a persistent context.
145
146               use Lexical::Persistence;
147
148               my $lp = Lexical::Persistence->new();
149               $lp->set_context(
150                       _ => {
151                               '@mind' => [qw(My mind is going. I can feel it.)]
152                       }
153               );
154
155               while (1) {
156                       $lp->call(\&display);
157                       my $mind = $lp->get_context("_")->{'@mind'};
158                       splice @$mind, rand(@$mind), 1;
159                       last unless @$mind;
160               }
161
162               sub display {
163                       my @mind;
164                       print "@mind\n";
165               }
166
167       Displays something like:
168
169               My mind is going. I can feel it.
170               My is going. I can feel it.
171               My is going. I feel it.
172               My going. I feel it.
173               My going. I feel
174               My I feel
175               My I
176               My
177
178       It's possible to create multiple Lexical::Persistence objects, each
179       with a unique state.
180
181               use Lexical::Persistence;
182
183               my $lp_1 = Lexical::Persistence->new();
184               $lp_1->set_context( _ => { '$foo' => "context 1's foo" } );
185
186               my $lp_2 = Lexical::Persistence->new();
187               $lp_2->set_context( _ => { '$foo' => "the foo in context 2" } );
188
189               $lp_1->call(\&display);
190               $lp_2->call(\&display);
191
192               sub display {
193                       print my $foo, "\n";
194               }
195
196       Gets you this output:
197
198               context 1's foo
199               the foo in context 2
200
201       You can also compile and execute perl code contained in plain strings
202       in a a lexical environment that already contains the persisted
203       variables.
204
205               use Lexical::Persistence;
206
207               my $lp = Lexical::Persistence->new();
208
209               $lp->do( 'my $message = "Hello, world" );
210
211               $lp->do( 'print "$message\n"' );
212
213       Which gives the output:
214
215               Hello, world
216
217       If you come up with other fun uses, let us know.
218
219   new
220       Create a new lexical persistence object.  This object will store one or
221       more persistent contexts.  When called by this object, lexical
222       variables will take on the values kept in this object.
223
224   initialize_contexts
225       This method is called by new() to declare the initial contexts for a
226       new Lexical::Persistence object.  The default implementation declares
227       the default "_" context.
228
229       Override or extend it to create others as needed.
230
231   set_context NAME, HASH
232       Store a context HASH within the persistence object, keyed on a NAME.
233       Members of the context HASH are unprefixed versions of the lexicals
234       they'll persist, including the sigil.  For example, this set_context()
235       call declares a "request" context with predefined values for three
236       variables: $request_foo, @request_foo, and %request_foo:
237
238               $lp->set_context(
239                       request => {
240                               '$foo' => 'value of $request_foo',
241                               '@foo' => [qw( value of @request_foo )],
242                               '%foo' => { key => 'value of $request_foo{key}' }
243                       }
244               );
245
246       See parse_variable() for information about how Lexical::Persistence
247       decides which context a lexical belongs to and how you can change that.
248
249   get_context NAME
250       Returns a context hash associated with a particular context name.
251       Autovivifies the context if it doesn't already exist, so be careful
252       there.
253
254   call CODEREF, ARGUMENT_LIST
255       Call CODEREF with lexical persistence and an optional ARGUMENT_LIST,
256       consisting of name => value pairs.  Unlike with set_context(), however,
257       argument names do not need sigils.  This may change in the future,
258       however, as it's easy to access an argument with the wrong variable
259       type.
260
261       The ARGUMENT_LIST is passed to the called CODEREF through @_ in the
262       usual way.  They're also available as $arg_name variables for
263       convenience.
264
265       See push_arg_context() for information about how $arg_name works, and
266       what you can do to change that behavior.
267
268   invoke OBJECT, METHOD, ARGUMENT_LIST
269       Invoke OBJECT->METHOD(ARGUMENT_LIST) while maintaining state for the
270       METHOD's lexical variables.  Written in terms of call(), except that it
271       takes OBJECT and METHOD rather than CODEREF.  See call() for more
272       details.
273
274       May have issues with methods invoked via AUTOLOAD, as invoke() uses
275       can() to find the method's CODEREF for call().
276
277   wrap CODEREF
278       Wrap a function or anonymous CODEREF so that it's transparently called
279       via call().  Returns a coderef which can be called directly.  Named
280       arguments to the call will automatically become available as $arg_name
281       lexicals within the called CODEREF.
282
283       See call() and push_arg_context() for more details.
284
285   prepare CODE
286       Wrap a CODE string in a subroutine definition, and prepend declarations
287       for all the variables stored in the Lexical::Persistence default
288       context.  This avoids having to declare variables explicitly in the
289       code using 'my'.  Returns a new code string ready for Perl's built-in
290       eval().  From there, a program may $lp->call() the code or $lp->wrap()
291       it.
292
293       Also see "compile()", which is a convenient wrapper for prepare() and
294       Perl's built-in eval().
295
296       Also see "do()", which is a convenient way to prepare(), eval() and
297       call() in one step.
298
299   compile CODE
300       compile() is a convenience method to prepare() a CODE string, eval()
301       it, and then return the resulting coderef.  If it fails, it returns
302       false, and $@ will explain why.
303
304   do CODE
305       do() is a convenience method to compile() a CODE string and execute it.
306       It returns the result of CODE's execution, or it throws an exception on
307       failure.
308
309       This example prints the numbers 1 through 10.  Note, however, that do()
310       compiles the same code each time.
311
312               use Lexical::Persistence;
313
314               my $lp = Lexical::Persistence->new();
315               $lp->do('my $count = 0');
316               $lp->do('print ++$count, "\\n"') for 1..10;
317
318       Lexical declarations are preserved across do() invocations, such as
319       with $count in the surrounding examples.  This behavior is part of
320       prepare(), which do() uses via compile().
321
322       The previous example may be rewritten in terms of compile() and call()
323       to avoid recompiling code every iteration.  Lexical declarations are
324       preserved between do() and compile() as well:
325
326               use Lexical::Persistence;
327
328               my $lp = Lexical::Persistence->new();
329               $lp->do('my $count = 0');
330               my $coderef = $lp->compile('print ++$count, "\\n"');
331               $lp->call($coderef) for 1..10;
332
333       do() inherits some limitations from PadWalker's peek_sub().  For
334       instance, it cannot alias lexicals within sub() definitions in the
335       supplied CODE string.  However, Lexical::Persistence can do this with
336       careful use of eval() and some custom CODE preparation.
337
338   parse_variable VARIABLE_NAME
339       This method determines whether VARIABLE_NAME should be persistent.  If
340       it should, parse_variable() will return three values: the variable's
341       sigil ('$', '@' or '%'), the context name in which the variable
342       persists (see set_context()), and the name of the member within that
343       context where the value is stored.  parse_variable() returns nothing if
344       VARIABLE_NAME should not be persistent.
345
346       parse_variable() also determines whether the member name includes its
347       sigil.  By default, the "arg" context is the only one with members that
348       have no sigils.  This is done to support the unadorned argument names
349       used by call().
350
351       This method implements a default behavior.  It's intended to be
352       overridden or extended by subclasses.
353
354   get_member_ref SIGIL, CONTEXT, MEMBER
355       This method fetches a reference to the named MEMBER of a particular
356       named CONTEXT.  The returned value type will be governed by the given
357       SIGIL.
358
359       Scalar values are stored internally as scalars to be consistent with
360       how most people store scalars.
361
362       The persistent value is created if it doesn't exist.  The initial value
363       is undef or empty, depending on its type.
364
365       This method implements a default behavior.  It's intended to be
366       overridden or extended by subclasses.
367
368   push_arg_context ARGUMENT_LIST
369       Convert a named ARGUMENT_LIST into members of an argument context, and
370       call set_context() to declare that context.  This is how $arg_foo
371       variables are supported.  This method returns the previous context,
372       fetched by get_context() before the new context is set.
373
374       This method implements a default behavior.  It's intended to be
375       overridden or extended by subclasses.  For example, to redefine the
376       parameters as $param_foo.
377
378       See pop_arg_context() for the other side of this coin.
379
380   pop_arg_context OLD_ARG_CONTEXT
381       Restores OLD_ARG_CONTEXT after a target function has returned.  The
382       OLD_ARG_CONTEXT is the return value from the push_arg_context() call
383       just prior to the target function's call.
384
385       This method implements a default behavior.  It's intended to be
386       overridden or extended by subclasses.
387

SEE ALSO

389       POE::Stage, Devel::LexAlias, PadWalker, Catalyst::Controller::BindLex.
390
391   BUG TRACKER
392       https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Lexical-Persistence
393
394   REPOSITORY
395       http://github.com/rcaputo/lexical-persistence
396       http://gitorious.org/lexical-persistence
397
398   OTHER RESOURCES
399       http://search.cpan.org/dist/Lexical-Persistence/
400
402       Lexical::Persistence in copyright 2006-2010 by Rocco Caputo.  All
403       rights reserved.  Lexical::Persistence is free software.  It is
404       released under the same terms as Perl itself.
405

ACKNOWLEDGEMENTS

407       Thanks to Matt Trout and Yuval Kogman for lots of inspiration.  They
408       were the demon and the other demon sitting on my shoulders.
409
410       Nick Perez convinced me to make this a class rather than persist with
411       the original, functional design.  While Higher Order Perl is fun for
412       development, I have to say the move to OO was a good one.
413
414       Paul "LeoNerd" Evans contributed the compile() and eval() methods.
415
416       The South Florida Perl Mongers, especially Jeff Bisbee and Marlon
417       Bailey, for documentation feedback.
418
419       irc://irc.perl.org/poe for support and feedback.
420
421
422
423perl v5.12.0                      2010-03-08           Lexical::Persistence(3)
Impressum