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
101 use Scope::Upper qw<uplevel CALLER>;
109 my $sub = (caller 0)[3];
110 print "$_[0] from $sub()";
114 target('hello'); # "hello from Uplevel::target()"
117 This module lets you defer actions *at run-time* that will take place
118 when the control flow returns into an upper scope. Currently, you can:
120 * hook an upper scope end with "reap" ;
122 * localize variables, array/hash values or deletions of elements in
123 higher contexts with respectively "localize", "localize_elem" and
126 * return values immediately to an upper level with "unwind", and know
127 which context was in use then with "want_at" ;
129 * execute a subroutine in the context of an upper subroutine stack
130 frame with "uplevel".
133 In all those functions, $context refers to the target scope.
135 You have to use one or a combination of "WORDS" to build the $context
136 passed to these functions. This is needed in order to ensure that the
137 module still works when your program is ran in the debugger. The only
138 thing you can assume is that it is an *absolute* indicator of the frame,
139 which means that you can safely store it at some point and use it when
140 needed, and it will still denote the original scope.
142 "reap $callback, $context"
143 Adds a destructor that calls $callback (in void context) when the upper
144 scope represented by $context ends.
146 "localize $what, $value, $context"
147 Introduces a "local" delayed to the time of first return into the upper
148 scope denoted by $context. $what can be :
150 * A glob, in which case $value can either be a glob or a reference.
151 "localize" follows then the same syntax as "local *x = $value". For
152 example, if $value is a scalar reference, then the "SCALAR" slot of
153 the glob will be set to $$value - just like "local *x = \1" sets $x
156 * A string beginning with a sigil, representing the symbol to localize
157 and to assign to. If the sigil is '$', "localize" follows the same
158 syntax as "local $x = $value", i.e. $value isn't dereferenced. For
161 localize '$x', \'foo' => HERE;
163 will set $x to a reference to the string 'foo'. Other sigils ('@',
164 '%', '&' and '*') require $value to be a reference of the
167 When the symbol is given by a string, it is resolved when the actual
168 localization takes place and not when "localize" is called. Thus, if
169 the symbol name is not qualified, it will refer to the variable in
170 the package where the localization actually takes place and not in
171 the one where the "localize" call was compiled. For example,
175 sub new { localize '$tag', $_[0] => UP }
186 will localize $Tool::tag and not $Scope::tag. If you want the other
187 behaviour, you just have to specify $what as a glob or a qualified
190 Note that if $what is a string denoting a variable that wasn't
191 declared beforehand, the relevant slot will be vivified as needed
192 and won't be deleted from the glob when the localization ends. This
193 situation never arises with "local" because it only compiles when
194 the localized variable is already declared. Although I believe it
195 shouldn't be a problem as glob slots definedness is pretty much an
196 implementation detail, this behaviour may change in the future if
199 "localize_elem $what, $key, $value, $context"
200 Introduces a "local $what[$key] = $value" or "local $what{$key} =
201 $value" delayed to the time of first return into the upper scope denoted
202 by $context. Unlike "localize", $what must be a string and the type of
203 localization is inferred from its sigil. The two only valid types are
204 array and hash ; for anything besides those, "localize_elem" will throw
205 an exception. $key is either an array index or a hash key, depending of
206 which kind of variable you localize.
208 If $what is a string pointing to an undeclared variable, the variable
209 will be vivified as soon as the localization occurs and emptied when it
210 ends, although it will still exist in its glob.
212 "localize_delete $what, $key, $context"
213 Introduces the deletion of a variable or an array/hash element delayed
214 to the time of first return into the upper scope denoted by $context.
217 * A glob, in which case $key is ignored and the call is equivalent to
220 * A string beginning with '@' or '%', for which the call is equivalent
221 to respectiveley "local $a[$key]; delete $a[$key]" and "local
222 $h{$key}; delete $h{$key}".
224 * A string beginning with '&', which more or less does "undef &func"
225 in the upper scope. It's actually more powerful, as &func won't even
226 "exists" anymore. $key is ignored.
228 "unwind @values, $context"
229 Returns @values *from* the context pointed by $context, i.e. from the
230 subroutine, eval or format at or just above $context, and immediately
231 restart the program flow at this point - thus effectively returning to
234 The upper context isn't coerced onto @values, which is hence always
235 evaluated in list context. This means that
238 my @a = ('a' .. 'z');
243 will set $num to 'z'. You can use "want_at" to handle these cases.
246 Like "wantarray", but for the subroutine/eval/format at or just above
249 The previous example can then be "corrected" :
252 my @a = ('a' .. 'z');
253 unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
257 will rightfully set $num to 26.
259 "uplevel $code, @args, $context"
260 Executes the code reference $code with arguments @args as if it were
261 located at the subroutine stack frame pointed by $context, effectively
262 fooling "caller" and "die" into believing that the call actually
263 happened higher in the stack. The code is executed in the context of the
264 "uplevel" call, and what it returns is returned as-is by "uplevel".
276 my @inverses = target(1, 2, 4); # @inverses contains (0, 0.5, 0.25)
277 my $count = target(1, 2, 4); # $target is 3
279 Sub::Uplevel also implements a pure-Perl version of "uplevel". Both are
280 identical, with the following caveats :
282 * The Sub::Uplevel implementation of "uplevel" may execute a code
283 reference in the context of any upper stack frame. The Scope::Upper
284 version only allows to uplevel to a subroutine stack frame, and will
285 croak if you try to target an "eval" or a format.
287 * Exceptions thrown from the code called by this version of "uplevel"
288 will not be caught by "eval" blocks between the target frame and the
289 uplevel call, while they will for Sub::Uplevel's version. This means
297 uplevel { die 'wut' } CALLER(2); # for Scope::Upper
298 # uplevel(3, sub { die 'wut' }) # for Sub::Uplevel
301 print "inner block: $@";
305 print "outer block: $@";
307 will print "inner block: wut..." with Sub::Uplevel and "outer block:
308 wut..." with Scope::Upper.
310 * Sub::Uplevel globally overrides "CORE::GLOBAL::caller", while
311 Scope::Upper does not.
313 A simple wrapper lets you mimic the interface of "uplevel" in
321 my $cxt = Scope::Upper::CALLER($frame);
322 &Scope::Upper::uplevel($code => @_ => $cxt);
325 Albeit the three exceptions listed above, it passes all the tests of
330 True iff the module could have been built when thread-safety features.
335 Returns the context that currently represents the highest scope.
338 The context of the current scope.
340 Getting a context from a context
341 For any of those functions, $from is expected to be a context. When
342 omitted, it defaults to the the current context.
345 The context of the scope just above $from.
348 The context of the closest subroutine above $from. Note that $from is
349 returned if it is already a subroutine context ; hence "SUB SUB == SUB".
352 The context of the closest eval above $from. Note that $from is returned
353 if it is already an eval context ; hence "EVAL EVAL == EVAL".
355 Getting a context from a level
356 Here, $level should denote a number of scopes above the current one.
357 When omitted, it defaults to 0 and those functions return the same
361 The $level-th upper context, regardless of its type.
364 The context of the $level-th upper subroutine/eval/format. It kind of
365 corresponds to the context represented by "caller $level", but while
366 e.g. "caller 0" refers to the caller context, "CALLER 0" will refer to
367 the top scope in the current context.
370 Where "reap" fires depending on the $cxt :
376 reap \&cleanup => $cxt;
378 } # $cxt = SCOPE(0), or HERE
380 }->(); # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
382 }; # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
384 }->(); # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
387 Where "localize", "localize_elem" and "localize_delete" act depending on
394 localize '$x' => 1 => $cxt;
395 # $cxt = SCOPE(0), or HERE
398 # $cxt = SCOPE(1), or UP, or SUB, or CALLER, or CALLER(0)
401 # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1)
404 # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
407 # $cxt = SCOPE(4), UP SUB UP SUB, or UP SUB EVAL, or UP CALLER(2), or TOP
410 Where "unwind", "want_at" and "uplevel" point to depending on the $cxt:
416 unwind @things => $cxt; # or uplevel { ... } $cxt;
420 }->(); # $cxt = SCOPE(0 .. 1), or HERE, or UP, or SUB, or CALLER(0)
422 }; # $cxt = SCOPE(2), or UP UP, or UP SUB, or EVAL, or CALLER(1) (*)
424 }->(); # $cxt = SCOPE(3), or SUB UP SUB, or SUB EVAL, or CALLER(2)
427 # (*) Note that uplevel() will croak if you pass that scope frame,
428 # because it can't target eval scopes.
431 The functions "reap", "localize", "localize_elem", "localize_delete",
432 "unwind", "want_at" and "uplevel" are only exported on request, either
433 individually or by the tags ':funcs' and ':all'.
435 The constant "SU_THREADSAFE" is also only exported on request,
436 individually or by the tags ':consts' and ':all'.
438 Same goes for the words "TOP", "HERE", "UP", "SUB", "EVAL", "SCOPE" and
439 "CALLER" that are only exported on request, individually or by the tags
443 Be careful that local variables are restored in the reverse order in
444 which they were localized. Consider those examples:
448 reap sub { print $x } => HERE;
456 reap sub { $x = 2 } => HERE;
461 The first case is "solved" by moving the "local" before the "reap", and
462 the second by using "localize" instead of "reap".
464 The effects of "reap", "localize" and "localize_elem" can't cross
465 "BEGIN" blocks, hence calling those functions in "import" is deemed to
466 be useless. This is an hopeless case because "BEGIN" blocks are executed
467 once while localizing constructs should do their job at each run.
468 However, it's possible to hook the end of the current scope compilation
469 with B::Hooks::EndOfScope.
471 Some rare oddities may still happen when running inside the debugger. It
472 may help to use a perl higher than 5.8.9 or 5.10.0, as they contain some
473 context-related fixes.
476 XSLoader (standard since perl 5.006).
479 "local" in perlfunc, "Temporary Values via local()" in perlsub.
481 Alias, Hook::Scope, Scope::Guard, Guard.
483 Continuation::Escape is a thin wrapper around Scope::Upper that gives
484 you a continuation passing style interface to "unwind". It's easier to
485 use, but it requires you to have control over the scope where you want
490 Sub::Uplevel provides a pure-Perl implementation of "uplevel".
493 Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
495 You can contact me by mail or on "irc.perl.org" (vincent).
498 Please report any bugs or feature requests to "bug-scope-upper at
499 rt.cpan.org", or through the web interface at
500 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper>. I will be
501 notified, and then you'll automatically be notified of progress on your
502 bug as I make changes.
505 You can find documentation for this module with the perldoc command.
509 Tests code coverage report is available at
510 <http://www.profvince.com/perl/cover/Scope-Upper>.
513 Inspired by Ricardo Signes.
515 Thanks to Shawn M. Moore for motivation.
518 Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
520 This program is free software; you can redistribute it and/or modify it
521 under the same terms as Perl itself.