X-Git-Url: http://git.vpit.fr/?a=blobdiff_plain;f=samples%2Ftag.pl;h=0e39930d2f7c03eda3ba55ad5e4bbb1d47998039;hb=57746d0b3de44a1205902e433488c8a1afe69469;hp=03a2fbed8d1a791d28adb9924d561dcec3f87060;hpb=3ed219c71c41746b0a59a6217f8fbb3178b36edc;p=perl%2Fmodules%2FScope-Upper.git diff --git a/samples/tag.pl b/samples/tag.pl index 03a2fbe..0e39930 100644 --- a/samples/tag.pl +++ b/samples/tag.pl @@ -1,44 +1,65 @@ #!perl -package X; - use strict; use warnings; use blib; -use Scope::Upper qw/reap localize localize_elem localize_delete/; +package Scope; -sub desc { shift->{desc} } +use Scope::Upper qw; -sub set_tag { - my ($desc) = @_; +sub new { + my ($class, $name) = @_; - # First localize $x so that it gets destroyed last - localize '$x' => bless({ desc => $desc }, __PACKAGE__) => 1; + localize '$tag' => bless({ name => $name }, $class) => UP; - reap sub { - my $pkg = caller; - my $x = do { no strict 'refs'; ${$pkg.'::x'} }; # Get the $x in the scope - print $x->desc . ": done\n"; - } => 1; + reap { print Scope->tag->name, ": end\n" } UP; +} - localize_elem '%SIG', '__WARN__' => sub { - my $pkg = caller; - my $x = do { no strict 'refs'; ${$pkg.'::x'} }; # Get the $x in the scope - CORE::warn($x->desc . ': ' . join('', @_)); - } => 1; +# Get the tag stored in the caller namespace +sub tag { + my $l = 0; + my $pkg = __PACKAGE__; + $pkg = caller $l++ while $pkg eq __PACKAGE__; - localize_delete '@ARGV', $#ARGV => 1; # delete last @ARGV element + no strict 'refs'; + ${$pkg . '::tag'}; } -package main; +sub name { shift->{name} } -use strict; -use warnings; +# Locally capture warnings and reprint them with the name prefixed +sub catch { + localize_elem '%SIG', '__WARN__' => sub { + print Scope->tag->name, ': ', @_; + } => UP; +} + +# Locally clear @INC +sub private { + for (reverse 0 .. $#INC) { + # First UP is the for loop, second is the sub boundary + localize_delete '@INC', $_ => UP UP; + } +} + +package UserLand; { - X::set_tag('pie'); - # $x is now a X object, and @ARGV has one element less - warn 'what'; # warns "pie: what at ..." -} # "pie: done" is printed + Scope->new("top"); # initializes $UserLand::tag + + { + Scope->catch; + my $one = 1 + undef; # prints "top: Use of uninitialized value..." + + { + Scope->private; + eval { delete $INC{"Cwd.pm"}; require Cwd }; # blib loads Cwd + print $@; # prints "Can't locate Cwd.pm in @INC (@INC contains:) at..." + } + + require Cwd; # loads Cwd.pm + } + +} # prints "top: done"