eff_i_g has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl package Hasher; use Carp; use strict; use warnings; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; bless ($self, $class); return $self; } sub file { my $self = shift; if (@_) { $self->{file} = shift; } } sub _common { my $self = shift; (my $key = (caller(1))[3]) =~ s/.*:://; if (@_) { $self->{$key} = shift; } else { $self->{$key}->($self) if defined $self->{$key}; } } sub pre { my $self = shift; $self->_common(@_); } sub loop { my $self = shift; $self->_common(@_); } sub post { my $self = shift; $self->_common(@_); } sub hash { my $self = shift; croak 'file does not exist' if not -e $self->{file}; $self->{count} = 0; $self->{hash} = (); $self->pre(); open my $fh, '<', $self->{file} or croak "could not open $self +->{file}: $!"; while (my $record = <$fh>) { chomp $record; $self->{record} = $record; $self->loop(); $self->{hash}{ $self->{key} } = $self->{value}; ++$self->{count}; } $self->post(); return %{$self->{hash}}; } 1;
#!/usr/bin/perl use strict; use warnings; use Hasher; my $states = new Hasher(); $states->file('states'); $states->loop( sub { my $self = shift; ($self->{value}, $self->{key}) = split ' ', $self->{re +cord}, 2; $self->{key} = uc $self->{key}; } ); $states->post( sub { my $self = shift; print "hashed $self->{count} states\n"; } ); my %state = $states->hash(); map { print "$_ = $state{$_}\n"; } keys %state;
|
|---|