#!/usr/bin/env perl use v5.14; package The::Package { use Carp; use base "Exporter"; BEGIN { our @EXPORT = qw( my_generator foo takes_coderef ) }; my $scratchpad; sub my_generator (&) { $scratchpad = {}; shift->(); my $tmp = $scratchpad; undef $scratchpad; return $tmp; } sub foo ($) { croak "foo must be called within my_generator" unless $scratchpad; $scratchpad->{foo} = shift; } sub takes_coderef (&) { croak "takes_coderef must be called within my_generator" unless $scratchpad; $scratchpad->{coderef} = shift; } BEGIN { $INC{"The/Package.pm"} = __FILE__ }; }; use The::Package; use Data::Dumper; my $complex_result = my_generator { foo 'bar'; takes_coderef { ... }; }; print Dumper($complex_result); foo 'baz'; # Should not affect $complex_result. # Ideally, should croak, or not even compile.