1Scope::Upper(3)       User Contributed Perl Documentation      Scope::Upper(3)
2
3
4

NAME

6       Scope::Upper - Act on upper scopes.
7

VERSION

9       Version 0.10
10

SYNOPSIS

12           package X;
13
14           use Scope::Upper qw/reap localize localize_elem localize_delete :words/;
15
16           sub desc { shift->{desc} }
17
18           sub set_tag {
19            my ($desc) = @_;
20
21            # First localize $x so that it gets destroyed last
22            localize '$x' => bless({ desc => $desc }, __PACKAGE__) => UP; # one scope up
23
24            reap sub {
25             my $pkg = caller;
26             my $x = do { no strict 'refs'; ${$pkg.'::x'} }; # Get the $x in the scope
27             print $x->desc . ": done\n";
28            } => SCOPE 1; # same as UP here
29
30            localize_elem '%SIG', '__WARN__' => sub {
31             my $pkg = caller;
32             my $x = do { no strict 'refs'; ${$pkg.'::x'} }; # Get the $x in the scope
33             CORE::warn($x->desc . ': ' . join('', @_));
34            } => UP CALLER 0; # same as UP here
35
36            # delete last @ARGV element
37            localize_delete '@ARGV', -1 => UP SUB HERE; # same as UP here
38           }
39
40           package Y;
41
42           {
43            X::set_tag('pie');
44            # $x is now a X object, and @ARGV has one element less
45            warn 'what'; # warns "pie: what at ..."
46            ...
47           } # "pie: done" is printed
48
49           package Z;
50
51           use Scope::Upper qw/unwind want_at :words/;
52
53           sub try (&) {
54            my @result = shift->();
55            my $cx = SUB UP SUB;
56            unwind +(want_at($cx) ? @result : scalar @result) => $cx;
57           }
58
59           ...
60
61           sub zap {
62            try {
63             return @things; # returns to try() and then outside zap()
64             # not reached
65            }
66            # not reached
67           }
68
69           my @what = zap(); # @what contains @things
70

DESCRIPTION

72       This module lets you defer actions at run-time that will take place
73       when the control flow returns into an upper scope.  Currently, you can:
74
75       ·   hook an upper scope end with "reap" ;
76
77       ·   localize variables, array/hash values or deletions of elements in
78           higher contexts with respectively "localize", "localize_elem" and
79           "localize_delete" ;
80
81       ·   return values immediately to an upper level with "unwind", and know
82           which context was in use then with "want_at".
83

FUNCTIONS

85       In all those functions, $context refers to the target scope.
86
87       You have to use one or a combination of "WORDS" to build the $context
88       passed to these functions.  This is needed in order to ensure that the
89       module still works when your program is ran in the debugger.  The only
90       thing you can assume is that it is an absolute indicator of the frame,
91       which means that you can safely store it at some point and use it when
92       needed, and it will still denote the original scope.
93
94   "reap $callback, $context"
95       Add a destructor that calls $callback (in void context) when the upper
96       scope represented by $context ends.
97
98   "localize $what, $value, $context"
99       A "local" delayed to the time of first return into the upper scope
100       denoted by $context.  $what can be :
101
102       ·   A glob, in which case $value can either be a glob or a reference.
103           "localize" follows then the same syntax as "local *x = $value".
104           For example, if $value is a scalar reference, then the "SCALAR"
105           slot of the glob will be set to $$value - just like "local *x = \1"
106           sets $x to 1.
107
108       ·   A string beginning with a sigil, representing the symbol to
109           localize and to assign to.  If the sigil is '$', "localize" follows
110           the same syntax as "local $x = $value", i.e. $value isn't
111           dereferenced.  For example,
112
113               localize '$x', \'foo' => HERE;
114
115           will set $x to a reference to the string 'foo'.  Other sigils ('@',
116           '%', '&' and '*') require $value to be a reference of the
117           corresponding type.
118
119           When the symbol is given by a string, it is resolved when the
120           actual localization takes place and not when "localize" is called.
121           This means that
122
123               sub tag { localize '$x', $_[0] => UP }
124
125           will localize in the caller's namespace.
126
127   "localize_elem $what, $key, $value, $context"
128       Similar to "localize" but for array and hash elements.  If $what is a
129       glob, the slot to fill is determined from which type of reference
130       $value is ; otherwise it's inferred from the sigil.  $key is either an
131       array index or a hash key, depending of which kind of variable you
132       localize.
133
134   "localize_delete $what, $key, $context"
135       Similiar to "localize", but for deleting variables or array/hash
136       elements.  $what can be:
137
138       ·   A glob, in which case $key is ignored and the call is equivalent to
139           "local *x".
140
141       ·   A string beginning with '@' or '%', for which the call is
142           equivalent to respectiveley "local $a[$key]; delete $a[$key]" and
143           "local $h{$key}; delete $h{$key}".
144
145       ·   A string beginning with '&', which more or less does "undef &func"
146           in the upper scope.  It's actually more powerful, as &func won't
147           even "exists" anymore.  $key is ignored.
148
149   "unwind @values, $context"
150       Returns @values from the context pointed by $context, i.e. from the
151       subroutine, eval or format just above $context, and immediately restart
152       the program flow at this point - thus effectively returning to (or
153       from, depending on how you see it) an upper context.
154
155       The upper context isn't coerced onto @values, which is hence always
156       evaluated in list context.  This means that
157
158           my $num = sub {
159            my @a = ('a' .. 'z');
160            unwind @a => HERE;
161            # not reached
162           }->();
163
164       will set $num to 'z'.  You can use "want_at" to handle these cases.
165
166   "want_at $context"
167       Like "wantarray", but for the subroutine/eval/format just above
168       $context.
169
170       The previous example can then be "corrected" :
171
172           my $num = sub {
173            my @a = ('a' .. 'z');
174            unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
175            # not reached
176           }->();
177
178       will rightfully set $num to 26.
179

CONSTANTS

181   "SU_THREADSAFE"
182       True iff the module could have been built when thread-safety features.
183

WORDS

185   Constants
186       "TOP"
187
188       Returns the context that currently represents the highest scope.
189
190       "HERE"
191
192       The context of the current scope.
193
194   Getting a context from a context
195       For any of those functions, $from is expected to be a context.  When
196       omitted, it defaults to the the current context.
197
198       "UP $from"
199
200       The context of the scope just above $from.
201
202       "SUB $from"
203
204       The context of the closest subroutine above $from.  Note that $from is
205       returned if it is already a subroutine context ; hence "SUB SUB ==
206       SUB".
207
208       "EVAL $from"
209
210       The context of the closest eval above $from.  Note that $from is
211       returned if it is already an eval context ; hence "EVAL EVAL == EVAL".
212
213   Getting a context from a level
214       Here, $level should denote a number of scopes above the current one.
215       When omitted, it defaults to 0 and those functions return the same
216       context as "HERE".
217
218       "SCOPE $level"
219
220       The $level-th upper context, regardless of its type.
221
222       "CALLER $level"
223
224       The context of the $level-th upper subroutine/eval/format.  It kind of
225       corresponds to the context represented by "caller $level", but while
226       e.g. "caller 0" refers to the caller context, "CALLER 0" will refer to
227       the top scope in the current context.
228
229   Examples
230       Where "reap" fires depending on the $cxt :
231
232           sub {
233            eval {
234             sub {
235              {
236               reap \&cleanup => $cxt;
237               ...
238              }     # $cxt = SCOPE(0), or HERE
239              ...
240             }->(); # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
241             ...
242            };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
243            ...
244           }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
245           ...
246
247       Where "localize", "localize_elem" and "localize_delete" act depending
248       on the $cxt :
249
250           sub {
251            eval {
252             sub {
253              {
254               localize '$x' => 1 => $cxt;
255               # $cxt = SCOPE(0), or HERE
256               ...
257              }
258              # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
259              ...
260             }->();
261             # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
262             ...
263            };
264            # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
265            ...
266           }->();
267           # $cxt = SCOPE(4), UP SUB UP SUB, or UP SUB EVAL, or UP CALLER(2), or TOP
268           ...
269
270       Where "unwind" and "want_at" point to depending on the $cxt:
271
272           sub {
273            eval {
274             sub {
275              {
276               unwind @things => $cxt;
277               ...
278              }
279              ...
280             }->(); # $cxt = SCOPE(0 .. 1), or HERE, or UP, or SUB, or CALLER(0)
281             ...
282            };      # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
283            ...
284           }->();   # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
285           ...
286

EXPORT

288       The functions "reap", "localize", "localize_elem", "localize_delete",
289       "unwind" and "want_at" are only exported on request, either
290       individually or by the tags ':funcs' and ':all'.
291
292       The constant "SU_THREADSAFE" is also only exported on request,
293       individually or by the tags ':consts' and ':all'.
294
295       Same goes for the words "TOP", "HERE", "UP", "SUB", "EVAL", "SCOPE" and
296       "CALLER" that are only exported on request, individually or by the tags
297       ':words' and ':all'.
298

CAVEATS

300       Be careful that local variables are restored in the reverse order in
301       which they were localized.  Consider those examples:
302
303           local $x = 0;
304           {
305            reap sub { print $x } => HERE;
306            local $x = 1;
307            ...
308           }
309           # prints '0'
310           ...
311           {
312            local $x = 1;
313            reap sub { $x = 2 } => HERE;
314            ...
315           }
316           # $x is 0
317
318       The first case is "solved" by moving the "local" before the "reap", and
319       the second by using "localize" instead of "reap".
320
321       The effects of "reap", "localize" and "localize_elem" can't cross
322       "BEGIN" blocks, hence calling those functions in "import" is deemed to
323       be useless.  This is an hopeless case because "BEGIN" blocks are
324       executed once while localizing constructs should do their job at each
325       run.  However, it's possible to hook the end of the current scope
326       compilation with B::Hooks::EndOfScope.
327
328       Some rare oddities may still happen when running inside the debugger.
329       It may help to use a perl higher than 5.8.9 or 5.10.0, as they contain
330       some context-related fixes.
331

DEPENDENCIES

333       XSLoader (standard since perl 5.006).
334

SEE ALSO

336       Alias, Hook::Scope, Scope::Guard, Guard.
337
338       Continuation::Escape is a thin wrapper around Scope::Upper that gives
339       you a continuation passing style interface to "unwind".  It's easier to
340       use, but it requires you to have control over the scope where you want
341       to return.
342

AUTHOR

344       Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
345
346       You can contact me by mail or on "irc.perl.org" (vincent).
347

BUGS

349       Please report any bugs or feature requests to "bug-scope-upper at
350       rt.cpan.org", or through the web interface at
351       http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper
352       <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper>.  I will
353       be notified, and then you'll automatically be notified of progress on
354       your bug as I make changes.
355

SUPPORT

357       You can find documentation for this module with the perldoc command.
358
359           perldoc Scope::Upper
360
361       Tests code coverage report is available at
362       http://www.profvince.com/perl/cover/Scope-Upper
363       <http://www.profvince.com/perl/cover/Scope-Upper>.
364

ACKNOWLEDGEMENTS

366       Inspired by Ricardo Signes.
367
368       Thanks to Shawn M. Moore for motivation.
369
371       Copyright 2008,2009,2010 Vincent Pit, all rights reserved.
372
373       This program is free software; you can redistribute it and/or modify it
374       under the same terms as Perl itself.
375
376
377
378perl v5.12.0                      2010-01-18                   Scope::Upper(3)
Impressum