#!/usr/bin/perl package Hasher; use Carp; use strict; use warnings; sub new { my $class = shift; my $self = { @_ }; bless ($self, $class); return $self; } sub hash { my $self = shift; croak 'file does not exist' if not -e $self->{file}; my %data; $data{count} = 0; $data{hash} = {}; $self->{pre}->(\%data) if $self->_verify('pre'); open my $fh, '<', $self->{file} or croak "could not open $self->{fi le}: $!"; while (<$fh>) { chomp; $data{record} = $_; $self->{loop}->(\%data) if $self->_verify('loop'); ++$data{count}; } $self->{post}->(\%data) if $self->_verify('post'); return %{$data{hash}}; } sub _verify { my $self = shift; my $key = shift; return 1 if ( exists $self->{$key} && ref($self->{$key}) eq 'CODE' ); return 0; } 1; #### #!/usr/bin/perl use strict; use warnings; use Hasher; my $states = Hasher->new( file => 'states', loop => sub { my $data_ref = shift; my ($value, $key) = split ' ', $data_ref->{record}, 2; $data_ref->{hash}->{ uc $key } = $value; }, post => sub { my $data_ref = shift; print "hashed $data_ref->{count} states\n"; } ); my %state = $states->hash(); map { print "$_ = $state{$_}\n"; } keys %state;