Suppose you have an object built around a complex hash. For some reason, you want to give other objects access to only part of it -- but you don't want to go through variable scoping or enforced encapsulation. Try this technique to make mini-objects.

Notes:

As for the tests, note that we display the keys for the top level object. Then, we display the keys for the newly created child object. Finally, we update a key nominally in the child object through the top object, and demonstrate that it is updated in the child object. No real thrill here, if you understand references, but a big caveat if you don't.

This one might be useful, somewhere.

#!/usr/bin/perl -w use strict; package SliceMe; sub new { my $class = shift; $class = ref($class) || $class; my $self = { 'top' => '1', 'nest1' => { 'hi' => '1', 'there' => '2' }, 'nest2' => { 'nest2a' => { 'first' => '1', 'second' => '2', }, 'nest2b' => 'not here' }, 'bottom' => '1', }; bless ($self, $class); return $self; } sub slice { my $self = shift; my $class = ref($self) || $self; my $key = shift; my $hash; $hash = _pare($self, $key); bless ($hash, $class) if defined $hash; return $hash; } sub _pare { my $hash_ref = shift; my $key = shift;  if (exists $hash_ref->{$key}) { return $hash_ref->{$key}; } else { foreach my $try_hash (keys %$hash_ref) { _pare($try_hash, $key); } return undef; } } package main; my $obj = new SliceMe; print "obj keys:\n"; print "\t$_\n" foreach (keys %$obj); my $obj_nest2 = $obj->slice("nest2"); print "obj_nest2 keys:\n"; print "\t$_\n" foreach (keys %$obj_nest2); foreach (keys %$obj_nest2) { print "$_\t=>\t", $obj_nest2->{$_}, "\n"; } $obj->{nest2}->{nest2b} = "okay, here now"; print $obj_nest2->{nest2b}, "\n";