use strict; use Tie::Hash; use Carp; package AccessControl; @AccessControl::ISA = 'Tie::StdHash'; sub allowVivification { $_[0]->{__novivify} = not $_[1] } sub TIEHASH { bless { __novivify => 0 }, $_[0] } sub STORE { my ( $self, $key, $value ) = @_; if ( $self->{__novivify} ) { unless ( exists( $self->{$key} ) ) { Carp::carp("Autovivification of key $key not allowed"); return; } } $self->{$key} = $value; } sub FIRSTKEY { my $a = scalar keys %{ $_[0] }; # reset each iterator my $key = each %{ $_[0] }; $key eq '__novivify' ? each %{ $_[0] } : $key; } sub NEXTKEY { my $key = each %{ $_[0] }; $key eq '__novivify' ? each %{ $_[0] } : $key; } package main; my %hash; my $accessControl = tie %hash, 'AccessControl'; $hash{abc} = 'def'; # OK $accessControl->allowVivification(0); $hash{ghi} = 'xxx'; # carps $accessControl->allowVivification(1); $hash{jkl} = 'yyy'; # OK print join ( ' ', keys(%hash) ), "\n"; # abc jkl