2 Scope::Upper - Act on upper scopes.
8 "reap", "localize", "localize_elem", "localize_delete" and "WORDS" :
13 reap localize localize_elem localize_delete
18 my ($class, $name) = @_;
20 localize '$tag' => bless({ name => $name }, $class) => UP;
22 reap { print Scope->tag->name, ": end\n" } UP;
25 # Get the tag stored in the caller namespace
28 my $pkg = __PACKAGE__;
29 $pkg = caller $l++ while $pkg eq __PACKAGE__;
35 sub name { shift->{name} }
37 # Locally capture warnings and reprint them with the name prefixed
39 localize_elem '%SIG', '__WARN__' => sub {
40 print Scope->tag->name, ': ', @_;
46 for (reverse 0 .. $#INC) {
47 # First UP is the for loop, second is the sub boundary
48 localize_delete '@INC', $_ => UP UP;
57 Scope->new("top"); # initializes $UserLand::tag
61 my $one = 1 + undef; # prints "top: Use of uninitialized value..."
66 print $@; # prints "Can't locate Cwd.pm in @INC
67 } # (@INC contains:) at..."
69 require Cwd; # loads Cwd.pm
72 } # prints "top: done"
74 "unwind" and "want_at" :
78 use Scope::Upper qw<unwind want_at :words>;
81 my @result = shift->();
82 my $cx = SUB UP; # Point to the sub above this one
83 unwind +(want_at($cx) ? @result : scalar @result) => $cx;
90 my @things = qw<a b c>;
91 return @things; # returns to try() and then outside zap()
97 my @stuff = zap(); # @stuff contains qw<a b c>
98 my $stuff = zap(); # $stuff contains 3
104 use Scope::Upper qw<uplevel CALLER>;
112 my $sub = (caller 0)[3];
113 print "$_[0] from $sub()";
117 target('hello'); # "hello from Uplevel::target()"
119 "uid" and "validate_uid" :
121 use Scope::Upper qw<uid validate_uid>;
128 if ($uid eq uid(UP)) { # yes
131 if (validate_uid($uid)) { # yes
137 if (validate_uid($uid)) { # no
142 This module lets you defer actions *at run-time* that will take place
143 when the control flow returns into an upper scope. Currently, you can:
145 * hook an upper scope end with "reap" ;
147 * localize variables, array/hash values or deletions of elements in
148 higher contexts with respectively "localize", "localize_elem" and
151 * return values immediately to an upper level with "unwind", and know
152 which context was in use then with "want_at" ;
154 * execute a subroutine in the setting of an upper subroutine stack
155 frame with "uplevel" ;
157 * uniquely identify contextes with "uid" and "validate_uid".
160 In all those functions, $context refers to the target scope.
162 You have to use one or a combination of "WORDS" to build the $context
163 passed to these functions. This is needed in order to ensure that the
164 module still works when your program is ran in the debugger. The only
165 thing you can assume is that it is an *absolute* indicator of the frame,
166 which means that you can safely store it at some point and use it when
167 needed, and it will still denote the original scope.
169 "reap $callback, $context"
170 Adds a destructor that calls $callback (in void context) when the upper
171 scope represented by $context ends.
173 "localize $what, $value, $context"
174 Introduces a "local" delayed to the time of first return into the upper
175 scope denoted by $context. $what can be :
177 * A glob, in which case $value can either be a glob or a reference.
178 "localize" follows then the same syntax as "local *x = $value". For
179 example, if $value is a scalar reference, then the "SCALAR" slot of
180 the glob will be set to $$value - just like "local *x = \1" sets $x
183 * A string beginning with a sigil, representing the symbol to localize
184 and to assign to. If the sigil is '$', "localize" follows the same
185 syntax as "local $x = $value", i.e. $value isn't dereferenced. For
188 localize '$x', \'foo' => HERE;
190 will set $x to a reference to the string 'foo'. Other sigils ('@',
191 '%', '&' and '*') require $value to be a reference of the
194 When the symbol is given by a string, it is resolved when the actual
195 localization takes place and not when "localize" is called. Thus, if
196 the symbol name is not qualified, it will refer to the variable in
197 the package where the localization actually takes place and not in
198 the one where the "localize" call was compiled. For example,
202 sub new { localize '$tag', $_[0] => UP }
213 will localize $Tool::tag and not $Scope::tag. If you want the other
214 behaviour, you just have to specify $what as a glob or a qualified
217 Note that if $what is a string denoting a variable that wasn't
218 declared beforehand, the relevant slot will be vivified as needed
219 and won't be deleted from the glob when the localization ends. This
220 situation never arises with "local" because it only compiles when
221 the localized variable is already declared. Although I believe it
222 shouldn't be a problem as glob slots definedness is pretty much an
223 implementation detail, this behaviour may change in the future if
226 "localize_elem $what, $key, $value, $context"
227 Introduces a "local $what[$key] = $value" or "local $what{$key} =
228 $value" delayed to the time of first return into the upper scope denoted
229 by $context. Unlike "localize", $what must be a string and the type of
230 localization is inferred from its sigil. The two only valid types are
231 array and hash ; for anything besides those, "localize_elem" will throw
232 an exception. $key is either an array index or a hash key, depending of
233 which kind of variable you localize.
235 If $what is a string pointing to an undeclared variable, the variable
236 will be vivified as soon as the localization occurs and emptied when it
237 ends, although it will still exist in its glob.
239 "localize_delete $what, $key, $context"
240 Introduces the deletion of a variable or an array/hash element delayed
241 to the time of first return into the upper scope denoted by $context.
244 * A glob, in which case $key is ignored and the call is equivalent to
247 * A string beginning with '@' or '%', for which the call is equivalent
248 to respectiveley "local $a[$key]; delete $a[$key]" and "local
249 $h{$key}; delete $h{$key}".
251 * A string beginning with '&', which more or less does "undef &func"
252 in the upper scope. It's actually more powerful, as &func won't even
253 "exists" anymore. $key is ignored.
255 "unwind @values, $context"
256 Returns @values *from* the context pointed by $context, i.e. from the
257 subroutine, eval or format at or just above $context, and immediately
258 restart the program flow at this point - thus effectively returning to
261 The upper context isn't coerced onto @values, which is hence always
262 evaluated in list context. This means that
265 my @a = ('a' .. 'z');
270 will set $num to 'z'. You can use "want_at" to handle these cases.
273 Like "wantarray", but for the subroutine/eval/format at or just above
276 The previous example can then be "corrected" :
279 my @a = ('a' .. 'z');
280 unwind +(want_at(HERE) ? @a : scalar @a) => HERE;
284 will rightfully set $num to 26.
286 "uplevel $code, @args, $context"
287 Executes the code reference $code with arguments @args as if it were
288 located at the subroutine stack frame pointed by $context, effectively
289 fooling "caller" and "die" into believing that the call actually
290 happened higher in the stack. The code is executed in the context of the
291 "uplevel" call, and what it returns is returned as-is by "uplevel".
303 my @inverses = target(1, 2, 4); # @inverses contains (0, 0.5, 0.25)
304 my $count = target(1, 2, 4); # $count is 3
306 Sub::Uplevel also implements a pure-Perl version of "uplevel". Both are
307 identical, with the following caveats :
309 * The Sub::Uplevel implementation of "uplevel" may execute a code
310 reference in the context of any upper stack frame. The Scope::Upper
311 version can only uplevel to a subroutine stack frame, and will croak
312 if you try to target an "eval" or a format.
314 * Exceptions thrown from the code called by this version of "uplevel"
315 will not be caught by "eval" blocks between the target frame and the
316 uplevel call, while they will for Sub::Uplevel's version. This means
324 uplevel { die 'wut' } CALLER(2); # for Scope::Upper
325 # uplevel(3, sub { die 'wut' }) # for Sub::Uplevel
328 print "inner block: $@";
332 print "outer block: $@";
334 will print "inner block: wut..." with Sub::Uplevel and "outer block:
335 wut..." with Scope::Upper.
337 * Sub::Uplevel globally overrides the Perl keyword "caller", while
338 Scope::Upper does not.
340 A simple wrapper lets you mimic the interface of "uplevel" in
348 my $cxt = Scope::Upper::CALLER($frame);
349 &Scope::Upper::uplevel($code => @_ => $cxt);
352 Albeit the three exceptions listed above, it passes all the tests of
356 Returns an unique identifier (UID) for the context (or dynamic scope)
357 pointed by $context, or for the current context if $context is omitted.
358 This UID will only be valid for the life time of the context it
359 represents, and another UID will be generated next time the same scope
366 if ($uid eq uid()) { # yes, this is the same context
370 if ($uid eq uid()) { # no, we are one scope below
373 if ($uid eq uid(UP)) { # yes, UP points to the same scope as $uid
379 # $uid is now invalid
382 if ($uid eq uid()) { # no, this is another block
387 For example, each loop iteration gets its own UID :
396 # %uids has 5 entries
398 The UIDs are not guaranteed to be numbers, so you must use the "eq"
399 operator to compare them.
401 To check whether a given UID is valid, you can use the "validate_uid"
405 Returns true if and only if $uid is the UID of a currently valid context
406 (that is, it designates a scope that is higher than the current one in
413 if (validate_uid($uid)) { # yes
417 if (validate_uid($uid)) { # yes
423 if (validate_uid($uid)) { # no
429 True iff the module could have been built when thread-safety features.
434 Returns the context that currently represents the highest scope.
437 The context of the current scope.
439 Getting a context from a context
440 For any of those functions, $from is expected to be a context. When
441 omitted, it defaults to the the current context.
444 The context of the scope just above $from.
447 The context of the closest subroutine above $from. Note that $from is
448 returned if it is already a subroutine context ; hence "SUB SUB == SUB".
451 The context of the closest eval above $from. Note that $from is returned
452 if it is already an eval context ; hence "EVAL EVAL == EVAL".
454 Getting a context from a level
455 Here, $level should denote a number of scopes above the current one.
456 When omitted, it defaults to 0 and those functions return the same
460 The $level-th upper context, regardless of its type.
463 The context of the $level-th upper subroutine/eval/format. It kind of
464 corresponds to the context represented by "caller $level", but while
465 e.g. "caller 0" refers to the caller context, "CALLER 0" will refer to
466 the top scope in the current context.
469 Where "reap" fires depending on the $cxt :
475 reap \&cleanup => $cxt;
477 } # $cxt = SCOPE(0) = HERE
479 }->(); # $cxt = SCOPE(1) = UP = SUB = CALLER(0)
481 }; # $cxt = SCOPE(2) = UP UP = UP SUB = EVAL = CALLER(1)
483 }->(); # $cxt = SCOPE(3) = SUB UP SUB = SUB EVAL = CALLER(2)
486 Where "localize", "localize_elem" and "localize_delete" act depending on
493 localize '$x' => 1 => $cxt;
494 # $cxt = SCOPE(0) = HERE
497 # $cxt = SCOPE(1) = UP = SUB = CALLER(0)
500 # $cxt = SCOPE(2) = UP UP = UP SUB = EVAL = CALLER(1)
503 # $cxt = SCOPE(3) = SUB UP SUB = SUB EVAL = CALLER(2)
506 # $cxt = SCOPE(4), UP SUB UP SUB = UP SUB EVAL = UP CALLER(2) = TOP
509 Where "unwind", "want_at" and "uplevel" point to depending on the $cxt:
515 unwind @things => $cxt; # or uplevel { ... } $cxt;
519 }->(); # $cxt = SCOPE(0) = SCOPE(1) = HERE = UP = SUB = CALLER(0)
521 }; # $cxt = SCOPE(2) = UP UP = UP SUB = EVAL = CALLER(1) (*)
523 }->(); # $cxt = SCOPE(3) = SUB UP SUB = SUB EVAL = CALLER(2)
526 # (*) Note that uplevel() will croak if you pass that scope frame,
527 # because it cannot target eval scopes.
530 The functions "reap", "localize", "localize_elem", "localize_delete",
531 "unwind", "want_at" and "uplevel" are only exported on request, either
532 individually or by the tags ':funcs' and ':all'.
534 The constant "SU_THREADSAFE" is also only exported on request,
535 individually or by the tags ':consts' and ':all'.
537 Same goes for the words "TOP", "HERE", "UP", "SUB", "EVAL", "SCOPE" and
538 "CALLER" that are only exported on request, individually or by the tags
542 Be careful that local variables are restored in the reverse order in
543 which they were localized. Consider those examples:
547 reap sub { print $x } => HERE;
555 reap sub { $x = 2 } => HERE;
560 The first case is "solved" by moving the "local" before the "reap", and
561 the second by using "localize" instead of "reap".
563 The effects of "reap", "localize" and "localize_elem" can't cross
564 "BEGIN" blocks, hence calling those functions in "import" is deemed to
565 be useless. This is an hopeless case because "BEGIN" blocks are executed
566 once while localizing constructs should do their job at each run.
567 However, it's possible to hook the end of the current scope compilation
568 with B::Hooks::EndOfScope.
570 Some rare oddities may still happen when running inside the debugger. It
571 may help to use a perl higher than 5.8.9 or 5.10.0, as they contain some
572 context-related fixes.
574 Calling "goto" to replace an "uplevel"'d code frame does not work :
576 * for a "perl" older than the 5.8 series ;
578 * for a "DEBUGGING" "perl" run with debugging flags set (as in "perl
581 * when the runloop callback is replaced by another module.
583 In those three cases, "uplevel" will look for a "goto &sub" statement in
584 its callback and, if there is one, throw an exception before executing
587 Moreover, in order to handle "goto" statements properly, "uplevel"
588 currently has to suffer a run-time overhead proportional to the size of
589 the the callback in every case (with a small ratio), and proportional to
590 the size of all the code executed as the result of the "uplevel" call
591 (including subroutine calls inside the callback) when a "goto" statement
592 is found in the "uplevel" callback. Despite this shortcoming, this XS
593 version of "uplevel" should still run way faster than the pure-Perl
594 version from Sub::Uplevel.
597 XSLoader (standard since perl 5.006).
600 "local" in perlfunc, "Temporary Values via local()" in perlsub.
602 Alias, Hook::Scope, Scope::Guard, Guard.
606 Continuation::Escape is a thin wrapper around Scope::Upper that gives
607 you a continuation passing style interface to "unwind". It's easier to
608 use, but it requires you to have control over the scope where you want
614 Vincent Pit, "<perl at profvince.com>", <http://www.profvince.com>.
616 You can contact me by mail or on "irc.perl.org" (vincent).
619 Please report any bugs or feature requests to "bug-scope-upper at
620 rt.cpan.org", or through the web interface at
621 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Scope-Upper>. I will be
622 notified, and then you'll automatically be notified of progress on your
623 bug as I make changes.
626 You can find documentation for this module with the perldoc command.
630 Tests code coverage report is available at
631 <http://www.profvince.com/perl/cover/Scope-Upper>.
634 Inspired by Ricardo Signes.
636 Thanks to Shawn M. Moore for motivation.
639 Copyright 2008,2009,2010,2011 Vincent Pit, all rights reserved.
641 This program is free software; you can redistribute it and/or modify it
642 under the same terms as Perl itself.