2 Scope::Upper - Act on upper scopes.
8 "reap", "localize", "localize_elem", "localize_delete" and "WORDS" :
12 use Scope::Upper qw/reap localize localize_elem localize_delete :words/;
15 my ($class, $name) = @_;
17 localize '$tag' => bless({ name => $name }, $class) => UP;
19 reap { print Scope->tag->name, ": end\n" } UP;
22 # Get the tag stored in the caller namespace
25 my $pkg = __PACKAGE__;
26 $pkg = caller $l++ while $pkg eq __PACKAGE__;
32 sub name { shift->{name} }
34 # Locally capture warnings and reprint them with the name prefixed
36 localize_elem '%SIG', '__WARN__' => sub {
37 print Scope->tag->name, ': ', @_;
43 for (reverse 0 .. $#INC) {
44 # First UP is the for loop, second is the sub boundary
45 localize_delete '@INC', $_ => UP UP;
54 Scope->new("top"); # initializes $UserLand::tag
58 my $one = 1 + undef; # prints "top: Use of uninitialized value..."
63 print $@; # prints "Can't locate Cwd.pm in @INC (@INC contains:) at..."
66 require Cwd; # loads Cwd.pm
69 } # prints "top: done"
71 "unwind" and "want_at" :
75 use Scope::Upper qw/unwind want_at :words/;
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;
87 my @things = qw/a b c/;
88 return @things; # returns to try() and then outside zap()
94 my @stuff = zap(); # @stuff contains qw/a b c/
95 my $stuff = zap(); # $stuff contains 3
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:
101 * hook an upper scope end with "reap" ;
103 * localize variables, array/hash values or deletions of elements in
104 higher contexts with respectively "localize", "localize_elem" and
107 * return values immediately to an upper level with "unwind", and know
108 which context was in use then with "want_at".
111 In all those functions, $context refers to the target scope.
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.
120 "reap $callback, $context"
121 Adds a destructor that calls $callback (in void context) when the upper
122 scope represented by $context ends.
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 :
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
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
139 localize '$x', \'foo' => HERE;
141 will set $x to a reference to the string 'foo'. Other sigils ('@',
142 '%', '&' and '*') require $value to be a reference of the
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,
153 sub new { localize '$tag', $_[0] => UP }
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
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
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.
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.
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.
195 * A glob, in which case $key is ignored and the call is equivalent to
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}".
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.
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
212 The upper context isn't coerced onto @values, which is hence always
213 evaluated in list context. This means that
216 my @a = ('a' .. 'z');
221 will set $num to 'z'. You can use "want_at" to handle these cases.
224 Like "wantarray", but for the subroutine/eval/format at or just above
227 The previous example can then be "corrected" :
230 my @a = ('a' .. 'z');
231 unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
235 will rightfully set $num to 26.
239 True iff the module could have been built when thread-safety features.
244 Returns the context that currently represents the highest scope.
247 The context of the current scope.
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.
254 The context of the scope just above $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".
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".
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
270 The $level-th upper context, regardless of its type.
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.
279 Where "reap" fires depending on the $cxt :
285 reap \&cleanup => $cxt;
287 } # $cxt = SCOPE(0), or HERE
289 }->(); # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
291 }; # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
293 }->(); # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
296 Where "localize", "localize_elem" and "localize_delete" act depending on
303 localize '$x' => 1 => $cxt;
304 # $cxt = SCOPE(0), or HERE
307 # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
310 # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
313 # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
316 # $cxt = SCOPE(4), UP SUB UP SUB, or UP SUB EVAL, or UP CALLER(2), or TOP
319 Where "unwind" and "want_at" point to depending on the $cxt:
325 unwind @things => $cxt;
329 }->(); # $cxt = SCOPE(0 .. 1), or HERE, or UP, or SUB, or CALLER(0)
331 }; # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
333 }->(); # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
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'.
341 The constant "SU_THREADSAFE" is also only exported on request,
342 individually or by the tags ':consts' and ':all'.
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
349 Be careful that local variables are restored in the reverse order in
350 which they were localized. Consider those examples:
354 reap sub { print $x } => HERE;
362 reap sub { $x = 2 } => HERE;
367 The first case is "solved" by moving the "local" before the "reap", and
368 the second by using "localize" instead of "reap".
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.
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.
382 XSLoader (standard since perl 5.006).
385 "local" in perlfunc, "Temporary Values via local()" in perlsub.
387 Alias, Hook::Scope, Scope::Guard, Guard.
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
397 Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
399 You can contact me by mail or on "irc.perl.org" (vincent).
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.
409 You can find documentation for this module with the perldoc command.
413 Tests code coverage report is available at
414 <http://www.profvince.com/perl/cover/Scope-Upper>.
417 Inspired by Ricardo Signes.
419 Thanks to Shawn M. Moore for motivation.
422 Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
424 This program is free software; you can redistribute it and/or modify it
425 under the same terms as Perl itself.