package File::With::State; use strict; use warnings; use Scalar::Util qw( refaddr ); use base 'IO::File'; my %stash; # hold inside-out state sub new { my $class = shift; # create the object and rebless my $self = IO::File->new(); bless $self, $class; # initialize the object $stash{ refaddr $self } = {}; $self->open( @_ ) if @_; return $self; } sub stash { my ($self, $key, $value) = @_; return unless $key; $stash{ refaddr $self }{ $key } = $value if $value; return $stash{ refaddr $self }{ $key }; } # Note: this simple example is not thread-safe and also # needs a destructor to avoid leaking memory #### my $fh = File::With::State->new( 'some_file' ); my @lines = <$fh>; $fh->stash( line_count => scalar @lines );