Skip to content

Instantly share code, notes, and snippets.

@tima
Created December 1, 2010 05:52
Show Gist options
  • Save tima/723034 to your computer and use it in GitHub Desktop.
Save tima/723034 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use strict;
use warnings;
# A proof of concept for a next generation context object
# that doesn't require the use of local and direct access
# to the stash HASH reference.
#
# pros:
# no use of local
# no manual (error prone) stack management
#
# cons:
# cloning of entire stash structure each time is probably expensive
#
package Mock::Context;
use base 'Exporter';
use vars qw(@EXPORT @EXPORT_OK);
@EXPORT = @EXPORT_OK = qw(context_scope);
use Storable qw(dclone);
sub new { bless { stack => [] }, __PACKAGE__; }
sub stash {
my $ctx = shift;
my $stack = $ctx->{stack};
push @$stack, $_[0] if defined $_[0];
return @$stack[-1];
}
sub context_scope (&;@) {
my ( $code, $ctx ) = @_;
local $ctx->{stack} = dclone( $ctx->{stack} );
$code->();
}
package main;
my $ctx = Mock::Context->new;
$ctx->stash(40);
print $ctx->stash . "\n"; # value set
eval { # prove error would not foil the stash going back to its value
Mock::Context::context_scope { # temporary scope of context changes
$ctx->stash(72);
print $ctx->stash . "\n"; # locally scope value is set
die "!!!!";
}
$ctx;
};
print $@ if $@; # prove the "error" happened
print $ctx->stash . "\n"; # prove the stash was returned to its original value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment