File Coverage

blib/lib/Lexical/Persistence.pm
Criterion Covered Total %
statement 75 81 92.5
branch 22 32 68.7
condition 2 2 100.0
subroutine 19 20 95.0
pod 14 14 100.0
total 132 149 88.5


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Lexical::Persistence - Persistent lexical variable values for arbitrary calls.
4              
5             =head1 VERSION
6              
7             version 1.023
8              
9             =head1 SYNOPSIS
10              
11             #!/usr/bin/perl
12              
13             use Lexical::Persistence;
14              
15             my $persistence = Lexical::Persistence->new();
16             foreach my $number (qw(one two three four five)) {
17             $persistence->call(\&target, number => $number);
18             }
19              
20             exit;
21              
22             sub target {
23             my $arg_number; # Argument.
24             my $narf_x++; # Persistent.
25             my $_i++; # Dynamic.
26             my $j++; # Persistent.
27              
28             print "arg_number = $arg_number\n";
29             print "\tnarf_x = $narf_x\n";
30             print "\t_i = $_i\n";
31             print "\tj = $j\n";
32             }
33              
34             =head1 DESCRIPTION
35              
36             Lexical::Persistence does a few things, all related. Note that all
37             the behaviors listed here are the defaults. Subclasses can override
38             nearly every aspect of Lexical::Persistence's behavior.
39              
40             Lexical::Persistence lets your code access persistent data through
41             lexical variables. This example prints "some value" because the value
42             of $x persists in the $lp object between setter() and getter().
43              
44             use Lexical::Persistence;
45              
46             my $lp = Lexical::Persistence->new();
47             $lp->call(\&setter);
48             $lp->call(\&getter);
49              
50             sub setter { my $x = "some value" }
51             sub getter { print my $x, "\n" }
52              
53             Lexicals with leading underscores are not persistent.
54              
55             By default, Lexical::Persistence supports accessing data from multiple
56             sources through the use of variable prefixes. The set_context()
57             member sets each data source. It takes a prefix name and a hash of
58             key/value pairs. By default, the keys must have sigils representing
59             their variable types.
60              
61             use Lexical::Persistence;
62              
63             my $lp = Lexical::Persistence->new();
64             $lp->set_context( pi => { '$member' => 3.141 } );
65             $lp->set_context( e => { '@member' => [ 2, '.', 7, 1, 8 ] } );
66             $lp->set_context(
67             animal => {
68             '%member' => { cat => "meow", dog => "woof" }
69             }
70             );
71              
72             $lp->call(\&display);
73              
74             sub display {
75             my ($pi_member, @e_member, %animal_member);
76              
77             print "pi = $pi_member\n";
78             print "e = @e_member\n";
79             while (my ($animal, $sound) = each %animal_member) {
80             print "The $animal goes... $sound!\n";
81             }
82             }
83              
84             And the corresponding output:
85              
86             pi = 3.141
87             e = 2 . 7 1 8
88             The cat goes... meow!
89             The dog goes... woof!
90              
91             By default, call() takes a single subroutine reference and an optional
92             list of named arguments. The arguments will be passed directly to the
93             called subroutine, but Lexical::Persistence also makes the values
94             available from the "arg" prefix.
95              
96             use Lexical::Persistence;
97              
98             my %animals = (
99             snake => "hiss",
100             plane => "I'm Cartesian",
101             );
102              
103             my $lp = Lexical::Persistence->new();
104             while (my ($animal, $sound) = each %animals) {
105             $lp->call(\&display, animal => $animal, sound => $sound);
106             }
107              
108             sub display {
109             my ($arg_animal, $arg_sound);
110             print "The $arg_animal goes... $arg_sound!\n";
111             }
112              
113             And the corresponding output:
114              
115             The plane goes... I'm Cartesian!
116             The snake goes... hiss!
117              
118             Sometimes you want to call functions normally. The wrap() method will
119             wrap your function in a small thunk that does the call() for you,
120             returning a coderef.
121              
122             use Lexical::Persistence;
123              
124             my $lp = Lexical::Persistence->new();
125             my $thunk = $lp->wrap(\&display);
126              
127             $thunk->(animal => "squirrel", sound => "nuts");
128              
129             sub display {
130             my ($arg_animal, $arg_sound);
131             print "The $arg_animal goes... $arg_sound!\n";
132             }
133              
134             And the corresponding output:
135              
136             The squirrel goes... nuts!
137              
138             Prefixes are the characters leading up to the first underscore in a
139             lexical variable's name. However, there's also a default context
140             named underscore. It's literally "_" because the underscore is not
141             legal in a context name by default. Variables without prefixes, or
142             with prefixes that have not been previously defined by set_context(),
143             are stored in that context.
144              
145             The get_context() member returns a hash for a named context. This
146             allows your code to manipulate the values within a persistent context.
147              
148             use Lexical::Persistence;
149              
150             my $lp = Lexical::Persistence->new();
151             $lp->set_context(
152             _ => {
153             '@mind' => [qw(My mind is going. I can feel it.)]
154             }
155             );
156              
157             while (1) {
158             $lp->call(\&display);
159             my $mind = $lp->get_context("_")->{'@mind'};
160             splice @$mind, rand(@$mind), 1;
161             last unless @$mind;
162             }
163              
164             sub display {
165             my @mind;
166             print "@mind\n";
167             }
168              
169             Displays something like:
170              
171             My mind is going. I can feel it.
172             My is going. I can feel it.
173             My is going. I feel it.
174             My going. I feel it.
175             My going. I feel
176             My I feel
177             My I
178             My
179              
180             It's possible to create multiple Lexical::Persistence objects, each
181             with a unique state.
182              
183             use Lexical::Persistence;
184              
185             my $lp_1 = Lexical::Persistence->new();
186             $lp_1->set_context( _ => { '$foo' => "context 1's foo" } );
187              
188             my $lp_2 = Lexical::Persistence->new();
189             $lp_2->set_context( _ => { '$foo' => "the foo in context 2" } );
190              
191             $lp_1->call(\&display);
192             $lp_2->call(\&display);
193              
194             sub display {
195             print my $foo, "\n";
196             }
197              
198             Gets you this output:
199              
200             context 1's foo
201             the foo in context 2
202              
203             You can also compile and execute perl code contained in plain strings in a
204             a lexical environment that already contains the persisted variables.
205              
206             use Lexical::Persistence;
207              
208             my $lp = Lexical::Persistence->new();
209              
210             $lp->do( 'my $message = "Hello, world" );
211              
212             $lp->do( 'print "$message\n"' );
213              
214             Which gives the output:
215              
216             Hello, world
217              
218             If you come up with other fun uses, let us know.
219              
220             =cut
221              
222             package Lexical::Persistence;
223              
224 2     2   1902 use warnings;
  2         4  
  2         55  
225 2     2   10 use strict;
  2         2  
  2         85  
226              
227             our $VERSION = '1.020';
228              
229 2     2   1704 use Devel::LexAlias qw(lexalias);
  2         11529  
  2         138  
230 2     2   17 use PadWalker qw(peek_sub);
  2         5  
  2         2914  
231              
232             =head2 new
233              
234             Create a new lexical persistence object. This object will store one
235             or more persistent contexts. When called by this object, lexical
236             variables will take on the values kept in this object.
237              
238             =cut
239              
240             sub new {
241 2     2 1 24 my $class = shift;
242              
243 2         9 my $self = bless {
244             context => { },
245             }, $class;
246              
247 2         10 $self->initialize_contexts();
248              
249 2         6 return $self;
250             }
251              
252             =head2 initialize_contexts
253              
254             This method is called by new() to declare the initial contexts for a
255             new Lexical::Persistence object. The default implementation declares
256             the default "_" context.
257              
258             Override or extend it to create others as needed.
259              
260             =cut
261              
262             sub initialize_contexts {
263 2     2 1 5 my $self = shift;
264 2         8 $self->set_context( _ => { } );
265             }
266              
267             =head2 set_context NAME, HASH
268              
269             Store a context HASH within the persistence object, keyed on a NAME.
270             Members of the context HASH are unprefixed versions of the lexicals
271             they'll persist, including the sigil. For example, this set_context()
272             call declares a "request" context with predefined values for three
273             variables: $request_foo, @request_foo, and %request_foo:
274              
275             $lp->set_context(
276             request => {
277             '$foo' => 'value of $request_foo',
278             '@foo' => [qw( value of @request_foo )],
279             '%foo' => { key => 'value of $request_foo{key}' }
280             }
281             );
282              
283             See parse_variable() for information about how Lexical::Persistence
284             decides which context a lexical belongs to and how you can change
285             that.
286              
287             =cut
288              
289             sub set_context {
290 36     36 1 56 my ($self, $context_name, $context_hash) = @_;
291 36         100 $self->{context}{$context_name} = $context_hash;
292             }
293              
294             =head2 get_context NAME
295              
296             Returns a context hash associated with a particular context name.
297             Autovivifies the context if it doesn't already exist, so be careful
298             there.
299              
300             =cut
301              
302             sub get_context {
303 26     26 1 31 my ($self, $context_name) = @_;
304 26   100     125 $self->{context}{$context_name} ||= { };
305             }
306              
307             =head2 call CODEREF, ARGUMENT_LIST
308              
309             Call CODEREF with lexical persistence and an optional ARGUMENT_LIST,
310             consisting of name => value pairs. Unlike with set_context(),
311             however, argument names do not need sigils. This may change in the
312             future, however, as it's easy to access an argument with the wrong
313             variable type.
314              
315             The ARGUMENT_LIST is passed to the called CODEREF through @_ in the
316             usual way. They're also available as $arg_name variables for
317             convenience.
318              
319             See push_arg_context() for information about how $arg_name works, and
320             what you can do to change that behavior.
321              
322             =cut
323              
324             sub call {
325 16     16 1 414 my ($self, $sub, @args) = @_;
326              
327 16         37 my $old_arg_context = $self->push_arg_context(@args);
328              
329 16         97 my $pad = peek_sub($sub);
330 16         584 while (my ($var, $ref) = each %$pad) {
331 51 100       278 next unless my ($sigil, $context, $member) = $self->parse_variable($var);
332 42         136 lexalias(
333             $sub, $var, $self->get_member_ref($sigil, $context, $member)
334             );
335             }
336              
337 16 100       122 unless (defined wantarray) {
338 12         110 $sub->(@args);
339 12         16825 $self->pop_arg_context($old_arg_context);
340 12         76 return;
341             }
342              
343 4 50       9 if (wantarray) {
344 0         0 my @return = $sub->(@args);
345 0         0 $self->pop_arg_context($old_arg_context);
346 0         0 return @return;
347             }
348              
349 4         115 my $return = $sub->(@args);
350 4         10 $self->pop_arg_context($old_arg_context);
351 4         40 return $return;
352             }
353              
354             =head2 invoke OBJECT, METHOD, ARGUMENT_LIST
355              
356             Invoke OBJECT->METHOD(ARGUMENT_LIST) while maintaining state for the
357             METHOD's lexical variables. Written in terms of call(), except that
358             it takes OBJECT and METHOD rather than CODEREF. See call() for more
359             details.
360              
361             May have issues with methods invoked via AUTOLOAD, as invoke() uses
362             can() to find the method's CODEREF for call().
363              
364             =cut
365              
366             sub invoke {
367 3     3 1 30 my ($self, $object, $method, @args) = @_;
368 3 50       46 return unless defined( my $sub = $object->can($method) );
369 3         11 $self->call($sub, @args);
370             }
371              
372             =head2 wrap CODEREF
373              
374             Wrap a function or anonymous CODEREF so that it's transparently called
375             via call(). Returns a coderef which can be called directly. Named
376             arguments to the call will automatically become available as $arg_name
377             lexicals within the called CODEREF.
378              
379             See call() and push_arg_context() for more details.
380              
381             =cut
382              
383             sub wrap {
384 1     1 1 8 my ($self, $invocant, $method) = @_;
385              
386 1 50       4 if (ref($invocant) eq 'CODE') {
387             return sub {
388 3     3   16 $self->call($invocant, @_);
389 1         6 };
390             }
391              
392             # FIXME - Experimental method wrapper.
393             # TODO - Make it resolve the method at call time.
394             # TODO - Possibly make it generate dynamic facade classes.
395              
396             return sub {
397 0     0   0 $self->invoke($invocant, $method, @_);
398 0         0 };
399             }
400              
401             =head2 prepare CODE
402              
403             Wrap a CODE string in a subroutine definition, and prepend
404             declarations for all the variables stored in the Lexical::Persistence
405             default context. This avoids having to declare variables explicitly
406             in the code using 'my'. Returns a new code string ready for Perl's
407             built-in eval(). From there, a program may $lp->call() the code or
408             $lp->wrap() it.
409              
410             Also see L, which is a convenient wrapper for prepare()
411             and Perl's built-in eval().
412              
413             Also see L, which is a convenient way to prepare(), eval() and
414             call() in one step.
415              
416             =cut
417              
418             sub prepare {
419 8     8 1 10 my ($self, $code) = @_;
420              
421             # Don't worry about values because $self->call() will deal with them
422 7         27 my $vars = join(
423 8         20 " ", map { "my $_;" }
424 8         10 keys %{ $self->get_context('_') }
425             );
426              
427             # Declare the variables OUTSIDE the actual sub. The compiler will
428             # pull any into the sub that are actually used. Any that aren't will
429             # just get dropped at this point
430 8         613 return "$vars sub { $code }";
431             }
432              
433             =head2 compile CODE
434              
435             compile() is a convenience method to prepare() a CODE string, eval()
436             it, and then return the resulting coderef. If it fails, it returns
437             false, and $@ will explain why.
438              
439             =cut
440              
441             sub compile {
442 8     8 1 12 my ($self, $code) = @_;
443 8         158 return eval($self->prepare($code));
444             }
445              
446             =head2 do CODE
447              
448             do() is a convenience method to compile() a CODE string and execute
449             it. It returns the result of CODE's execution, or it throws an
450             exception on failure.
451              
452             This example prints the numbers 1 through 10. Note, however, that
453             do() compiles the same code each time.
454              
455             use Lexical::Persistence;
456              
457             my $lp = Lexical::Persistence->new();
458             $lp->do('my $count = 0');
459             $lp->do('print ++$count, "\\n"') for 1..10;
460              
461             Lexical declarations are preserved across do() invocations, such as
462             with $count in the surrounding examples. This behavior is part of
463             prepare(), which do() uses via compile().
464              
465             The previous example may be rewritten in terms of compile() and call()
466             to avoid recompiling code every iteration. Lexical declarations are
467             preserved between do() and compile() as well:
468              
469             use Lexical::Persistence;
470              
471             my $lp = Lexical::Persistence->new();
472             $lp->do('my $count = 0');
473             my $coderef = $lp->compile('print ++$count, "\\n"');
474             $lp->call($coderef) for 1..10;
475              
476             do() inherits some limitations from PadWalker's peek_sub(). For
477             instance, it cannot alias lexicals within sub() definitions in the
478             supplied CODE string. However, Lexical::Persistence can do this with
479             careful use of eval() and some custom CODE preparation.
480              
481             =cut
482              
483             sub do {
484 6     6 1 15 my ($self, $code) = @_;
485              
486 6 50       15 my $sub = $self->compile( $code ) or die $@;
487 6         17 $self->call( $sub );
488             }
489              
490             =head2 parse_variable VARIABLE_NAME
491              
492             This method determines whether VARIABLE_NAME should be persistent. If
493             it should, parse_variable() will return three values: the variable's
494             sigil ('$', '@' or '%'), the context name in which the variable
495             persists (see set_context()), and the name of the member within that
496             context where the value is stored. parse_variable() returns nothing
497             if VARIABLE_NAME should not be persistent.
498              
499             parse_variable() also determines whether the member name includes its
500             sigil. By default, the "arg" context is the only one with members
501             that have no sigils. This is done to support the unadorned argument
502             names used by call().
503              
504             This method implements a default behavior. It's intended to be
505             overridden or extended by subclasses.
506              
507             =cut
508              
509             sub parse_variable {
510 51     51 1 57 my ($self, $var) = @_;
511              
512             return unless (
513 51 100       880 my ($sigil, $context, $member) = (
514             $var =~ /^([\$\@\%])(?!_)(?:([^_]*)_)?(\S+)/
515             )
516             );
517              
518 42 100       91 if (defined $context) {
519 27 100       64 if (exists $self->{context}{$context}) {
520 18 100       54 return $sigil, $context, $member if $context eq "arg";
521 9         34 return $sigil, $context, "$sigil$member";
522             }
523 9         36 return $sigil, "_", "$sigil$context\_$member";
524             }
525              
526 15         67 return $sigil, "_", "$sigil$member";
527             }
528              
529             =head2 get_member_ref SIGIL, CONTEXT, MEMBER
530              
531             This method fetches a reference to the named MEMBER of a particular
532             named CONTEXT. The returned value type will be governed by the given
533             SIGIL.
534              
535             Scalar values are stored internally as scalars to be consistent with
536             how most people store scalars.
537              
538             The persistent value is created if it doesn't exist. The initial
539             value is undef or empty, depending on its type.
540              
541             This method implements a default behavior. It's intended to be
542             overridden or extended by subclasses.
543              
544             =cut
545              
546             sub get_member_ref {
547 42     42 1 70 my ($self, $sigil, $context, $member) = @_;
548              
549 42         68 my $hash = $self->{context}{$context};
550              
551 42 100       86 if ($sigil eq '$') {
552 41 100       71 $hash->{$member} = undef unless exists $hash->{$member};
553 41         140 return \$hash->{$member};
554             }
555              
556 1 50       5 if ($sigil eq '@') {
    0          
557 1 50       7 $hash->{$member} = [ ] unless exists $hash->{$member};
558             }
559             elsif ($sigil eq '%') {
560 0 0       0 $hash->{$member} = { } unless exists $hash->{$member};
561             }
562              
563 1         5 return $hash->{$member};
564             }
565              
566             =head2 push_arg_context ARGUMENT_LIST
567              
568             Convert a named ARGUMENT_LIST into members of an argument context, and
569             call set_context() to declare that context. This is how $arg_foo
570             variables are supported. This method returns the previous context,
571             fetched by get_context() before the new context is set.
572              
573             This method implements a default behavior. It's intended to be
574             overridden or extended by subclasses. For example, to redefine the
575             parameters as $param_foo.
576              
577             See pop_arg_context() for the other side of this coin.
578              
579             =cut
580              
581             sub push_arg_context {
582 16     16 1 19 my $self = shift;
583 16         36 my $old_arg_context = $self->get_context("arg");
584 16         46 $self->set_context( arg => { @_ } );
585 16         26 return $old_arg_context;
586             }
587              
588             =head2 pop_arg_context OLD_ARG_CONTEXT
589              
590             Restores OLD_ARG_CONTEXT after a target function has returned. The
591             OLD_ARG_CONTEXT is the return value from the push_arg_context() call
592             just prior to the target function's call.
593              
594             This method implements a default behavior. It's intended to be
595             overridden or extended by subclasses.
596              
597             =cut
598              
599             sub pop_arg_context {
600 16     16 1 29 my ($self, $old_context) = @_;
601 16         33 $self->set_context( arg => $old_context );
602             }
603              
604             =head1 SEE ALSO
605              
606             L, L, L,
607             L.
608              
609             =head2 BUG TRACKER
610              
611             https://rt.cpan.org/Dist/Display.html?Status=Active&Queue=Lexical-Persistence
612              
613             =head2 REPOSITORY
614              
615             http://github.com/rcaputo/lexical-persistence
616             http://gitorious.org/lexical-persistence
617              
618             =head2 OTHER RESOURCES
619              
620             http://search.cpan.org/dist/Lexical-Persistence/
621              
622             =head1 COPYRIGHT
623              
624             Lexical::Persistence in copyright 2006-2013 by Rocco Caputo. All
625             rights reserved. Lexical::Persistence is free software. It is
626             released under the same terms as Perl itself.
627              
628             =head1 ACKNOWLEDGEMENTS
629              
630             Thanks to Matt Trout and Yuval Kogman for lots of inspiration. They
631             were the demon and the other demon sitting on my shoulders.
632              
633             Nick Perez convinced me to make this a class rather than persist with
634             the original, functional design. While Higher Order Perl is fun for
635             development, I have to say the move to OO was a good one.
636              
637             Paul "LeoNerd" Evans contributed the compile() and eval() methods.
638              
639             The South Florida Perl Mongers, especially Jeff Bisbee and Marlon
640             Bailey, for documentation feedback.
641              
642             irc://irc.perl.org/poe for support and feedback.
643              
644             =cut
645              
646             1;