]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - README
This is 0.12
[perl/modules/Scope-Upper.git] / README
1 NAME
2     Scope::Upper - Act on upper scopes.
3
4 VERSION
5     Version 0.12
6
7 SYNOPSIS
8     "reap", "localize", "localize_elem", "localize_delete" and "WORDS" :
9
10         package Scope;
11
12         use Scope::Upper qw/reap localize localize_elem localize_delete :words/;
13
14         sub new {
15          my ($class, $name) = @_;
16
17          localize '$tag' => bless({ name => $name }, $class) => UP;
18
19          reap { print Scope->tag->name, ": end\n" } UP;
20         }
21
22         # Get the tag stored in the caller namespace
23         sub tag {
24          my $l   = 0;
25          my $pkg = __PACKAGE__;
26          $pkg    = caller $l++ while $pkg eq __PACKAGE__;
27
28          no strict 'refs';
29          ${$pkg . '::tag'};
30         }
31
32         sub name { shift->{name} }
33
34         # Locally capture warnings and reprint them with the name prefixed
35         sub catch {
36          localize_elem '%SIG', '__WARN__' => sub {
37           print Scope->tag->name, ': ', @_;
38          } => UP;
39         }
40
41         # Locally clear @INC
42         sub private {
43          for (reverse 0 .. $#INC) {
44           # First UP is the for loop, second is the sub boundary
45           localize_delete '@INC', $_ => UP UP;
46          }
47         }
48
49         ...
50
51         package UserLand;
52
53         {
54          Scope->new("top");      # initializes $UserLand::tag
55
56          {
57           Scope->catch;
58           my $one = 1 + undef;   # prints "top: Use of uninitialized value..."
59
60           {
61            Scope->private;
62            eval { require Cwd };
63            print $@;             # prints "Can't locate Cwd.pm in @INC (@INC contains:) at..."
64           }
65
66           require Cwd;           # loads Cwd.pm
67          }
68
69         }                        # prints "top: done"
70
71     "unwind" and "want_at" :
72
73         package Try;
74
75         use Scope::Upper qw/unwind want_at :words/;
76
77         sub try (&) {
78          my @result = shift->();
79          my $cx = SUB UP; # Point to the sub above this one
80          unwind +(want_at($cx) ? @result : scalar @result) => $cx;
81         }
82
83         ...
84
85         sub zap {
86          try {
87           my @things = qw/a b c/;
88           return @things; # returns to try() and then outside zap()
89           # not reached
90          };
91          # not reached
92         }
93
94         my @stuff = zap(); # @stuff contains qw/a b c/
95         my $stuff = zap(); # $stuff contains 3
96
97 DESCRIPTION
98     This module lets you defer actions *at run-time* that will take place
99     when the control flow returns into an upper scope. Currently, you can:
100
101     *   hook an upper scope end with "reap" ;
102
103     *   localize variables, array/hash values or deletions of elements in
104         higher contexts with respectively "localize", "localize_elem" and
105         "localize_delete" ;
106
107     *   return values immediately to an upper level with "unwind", and know
108         which context was in use then with "want_at".
109
110 FUNCTIONS
111     In all those functions, $context refers to the target scope.
112
113     You have to use one or a combination of "WORDS" to build the $context
114     passed to these functions. This is needed in order to ensure that the
115     module still works when your program is ran in the debugger. The only
116     thing you can assume is that it is an *absolute* indicator of the frame,
117     which means that you can safely store it at some point and use it when
118     needed, and it will still denote the original scope.
119
120   "reap $callback, $context"
121     Adds a destructor that calls $callback (in void context) when the upper
122     scope represented by $context ends.
123
124   "localize $what, $value, $context"
125     Introduces a "local" delayed to the time of first return into the upper
126     scope denoted by $context. $what can be :
127
128     *   A glob, in which case $value can either be a glob or a reference.
129         "localize" follows then the same syntax as "local *x = $value". For
130         example, if $value is a scalar reference, then the "SCALAR" slot of
131         the glob will be set to $$value - just like "local *x = \1" sets $x
132         to 1.
133
134     *   A string beginning with a sigil, representing the symbol to localize
135         and to assign to. If the sigil is '$', "localize" follows the same
136         syntax as "local $x = $value", i.e. $value isn't dereferenced. For
137         example,
138
139             localize '$x', \'foo' => HERE;
140
141         will set $x to a reference to the string 'foo'. Other sigils ('@',
142         '%', '&' and '*') require $value to be a reference of the
143         corresponding type.
144
145         When the symbol is given by a string, it is resolved when the actual
146         localization takes place and not when "localize" is called. Thus, if
147         the symbol name is not qualified, it will refer to the variable in
148         the package where the localization actually takes place and not in
149         the one where the "localize" call was compiled. For example,
150
151             {
152              package Scope;
153              sub new { localize '$tag', $_[0] => UP }
154             }
155
156             {
157              package Tool;
158              {
159               Scope->new;
160               ...
161              }
162             }
163
164         will localize $Tool::tag and not $Scope::tag. If you want the other
165         behaviour, you just have to specify $what as a glob or a qualified
166         name.
167
168         Note that if $what is a string denoting a variable that wasn't
169         declared beforehand, the relevant slot will be vivified as needed
170         and won't be deleted from the glob when the localization ends. This
171         situation never arises with "local" because it only compiles when
172         the localized variable is already declared. Although I believe it
173         shouldn't be a problem as glob slots definedness is pretty much an
174         implementation detail, this behaviour may change in the future if
175         proved harmful.
176
177   "localize_elem $what, $key, $value, $context"
178     Introduces a "local $what[$key] = $value" or "local $what{$key} =
179     $value" delayed to the time of first return into the upper scope denoted
180     by $context. Unlike "localize", $what must be a string and the type of
181     localization is inferred from its sigil. The two only valid types are
182     array and hash ; for anything besides those, "localize_elem" will throw
183     an exception. $key is either an array index or a hash key, depending of
184     which kind of variable you localize.
185
186     If $what is a string pointing to an undeclared variable, the variable
187     will be vivified as soon as the localization occurs and emptied when it
188     ends, although it will still exist in its glob.
189
190   "localize_delete $what, $key, $context"
191     Introduces the deletion of a variable or an array/hash element delayed
192     to the time of first return into the upper scope denoted by $context.
193     $what can be:
194
195     *   A glob, in which case $key is ignored and the call is equivalent to
196         "local *x".
197
198     *   A string beginning with '@' or '%', for which the call is equivalent
199         to respectiveley "local $a[$key]; delete $a[$key]" and "local
200         $h{$key}; delete $h{$key}".
201
202     *   A string beginning with '&', which more or less does "undef &func"
203         in the upper scope. It's actually more powerful, as &func won't even
204         "exists" anymore. $key is ignored.
205
206   "unwind @values, $context"
207     Returns @values *from* the context pointed by $context, i.e. from the
208     subroutine, eval or format at or just above $context, and immediately
209     restart the program flow at this point - thus effectively returning to
210     an upper scope.
211
212     The upper context isn't coerced onto @values, which is hence always
213     evaluated in list context. This means that
214
215         my $num = sub {
216          my @a = ('a' .. 'z');
217          unwind @a => HERE;
218          # not reached
219         }->();
220
221     will set $num to 'z'. You can use "want_at" to handle these cases.
222
223   "want_at $context"
224     Like "wantarray", but for the subroutine/eval/format at or just above
225     $context.
226
227     The previous example can then be "corrected" :
228
229         my $num = sub {
230          my @a = ('a' .. 'z');
231          unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
232          # not reached
233         }->();
234
235     will rightfully set $num to 26.
236
237 CONSTANTS
238   "SU_THREADSAFE"
239     True iff the module could have been built when thread-safety features.
240
241 WORDS
242   Constants
243    "TOP"
244     Returns the context that currently represents the highest scope.
245
246    "HERE"
247     The context of the current scope.
248
249   Getting a context from a context
250     For any of those functions, $from is expected to be a context. When
251     omitted, it defaults to the the current context.
252
253    "UP $from"
254     The context of the scope just above $from.
255
256    "SUB $from"
257     The context of the closest subroutine above $from. Note that $from is
258     returned if it is already a subroutine context ; hence "SUB SUB == SUB".
259
260    "EVAL $from"
261     The context of the closest eval above $from. Note that $from is returned
262     if it is already an eval context ; hence "EVAL EVAL == EVAL".
263
264   Getting a context from a level
265     Here, $level should denote a number of scopes above the current one.
266     When omitted, it defaults to 0 and those functions return the same
267     context as "HERE".
268
269    "SCOPE $level"
270     The $level-th upper context, regardless of its type.
271
272    "CALLER $level"
273     The context of the $level-th upper subroutine/eval/format. It kind of
274     corresponds to the context represented by "caller $level", but while
275     e.g. "caller 0" refers to the caller context, "CALLER 0" will refer to
276     the top scope in the current context.
277
278   Examples
279     Where "reap" fires depending on the $cxt :
280
281         sub {
282          eval {
283           sub {
284            {
285             reap \&cleanup => $cxt;
286             ...
287            }     # $cxt = SCOPE(0), or HERE
288            ...
289           }->(); # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
290           ...
291          };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
292          ...
293         }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
294         ...
295
296     Where "localize", "localize_elem" and "localize_delete" act depending on
297     the $cxt :
298
299         sub {
300          eval {
301           sub {
302            {
303             localize '$x' => 1 => $cxt;
304             # $cxt = SCOPE(0), or HERE
305             ...
306            }
307            # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
308            ...
309           }->();
310           # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
311           ...
312          };
313          # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
314          ...
315         }->();
316         # $cxt = SCOPE(4), UP SUB UP SUB, or UP SUB EVAL, or UP CALLER(2), or TOP
317         ...
318
319     Where "unwind" and "want_at" point to depending on the $cxt:
320
321         sub {
322          eval {
323           sub {
324            {
325             unwind @things => $cxt;
326             ...
327            }
328            ...
329           }->(); # $cxt = SCOPE(0 .. 1), or HERE, or UP, or SUB, or CALLER(0)
330           ...
331          };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
332          ...
333         }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
334         ...
335
336 EXPORT
337     The functions "reap", "localize", "localize_elem", "localize_delete",
338     "unwind" and "want_at" are only exported on request, either individually
339     or by the tags ':funcs' and ':all'.
340
341     The constant "SU_THREADSAFE" is also only exported on request,
342     individually or by the tags ':consts' and ':all'.
343
344     Same goes for the words "TOP", "HERE", "UP", "SUB", "EVAL", "SCOPE" and
345     "CALLER" that are only exported on request, individually or by the tags
346     ':words' and ':all'.
347
348 CAVEATS
349     Be careful that local variables are restored in the reverse order in
350     which they were localized. Consider those examples:
351
352         local $x = 0;
353         {
354          reap sub { print $x } => HERE;
355          local $x = 1;
356          ...
357         }
358         # prints '0'
359         ...
360         {
361          local $x = 1;
362          reap sub { $x = 2 } => HERE;
363          ...
364         }
365         # $x is 0
366
367     The first case is "solved" by moving the "local" before the "reap", and
368     the second by using "localize" instead of "reap".
369
370     The effects of "reap", "localize" and "localize_elem" can't cross
371     "BEGIN" blocks, hence calling those functions in "import" is deemed to
372     be useless. This is an hopeless case because "BEGIN" blocks are executed
373     once while localizing constructs should do their job at each run.
374     However, it's possible to hook the end of the current scope compilation
375     with B::Hooks::EndOfScope.
376
377     Some rare oddities may still happen when running inside the debugger. It
378     may help to use a perl higher than 5.8.9 or 5.10.0, as they contain some
379     context-related fixes.
380
381 DEPENDENCIES
382     XSLoader (standard since perl 5.006).
383
384 SEE ALSO
385     "local" in perlfunc, "Temporary Values via local()" in perlsub.
386
387     Alias, Hook::Scope, Scope::Guard, Guard.
388
389     Continuation::Escape is a thin wrapper around Scope::Upper that gives
390     you a continuation passing style interface to "unwind". It's easier to
391     use, but it requires you to have control over the scope where you want
392     to return.
393
394     Scope::Escape.
395
396 AUTHOR
397     Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
398
399     You can contact me by mail or on "irc.perl.org" (vincent).
400
401 BUGS
402     Please report any bugs or feature requests to "bug-scope-upper at
403     rt.cpan.org", or through the web interface at
404     <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper>. I will be
405     notified, and then you'll automatically be notified of progress on your
406     bug as I make changes.
407
408 SUPPORT
409     You can find documentation for this module with the perldoc command.
410
411         perldoc Scope::Upper
412
413     Tests code coverage report is available at
414     <http://www.profvince.com/perl/cover/Scope-Upper>.
415
416 ACKNOWLEDGEMENTS
417     Inspired by Ricardo Signes.
418
419     Thanks to Shawn M. Moore for motivation.
420
421 COPYRIGHT & LICENSE
422     Copyright 2008,2009,2010 Vincent Pit, all rights reserved.
423
424     This program is free software; you can redistribute it and/or modify it
425     under the same terms as Perl itself.
426